Public Group

This topic is 2154 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

code like this:

int * a = new int(0);
int * b = new int(0);
int * c = new int[2];
int * d = new int[2];
int * e = new int[1];
delete a;
delete []b;
delete c;
delete []d;
delete e;

The compiler does not prompt "error" or "warning"(vs 2005 at warning level 4).
But such use of "delete" and "delete []" is incorrect according the book(line "delete []b;" and "delete c;").
Is that so?what problem will cause?

Share on other sites

Well, it's undefined behaviour, so technically, while there is no guarantee it will work, there is no guarantee it will fail, either.

I suggest using it the right way, the reason it worked here is probably because int is a simple data type. If you were using a more complicated class, the new[] will create each element of the array as expected, and the delete[] will call the destructor of each element, whereas the delete would just free the array without calling the destructor for each element, which may result in a memory leak and possibly much worse errors. Again, just because it works, doesn't mean it's correct.

Also, I suppose the lack of compiler warnings comes from the fact that it's not always possible to distinguish an array from a pointer to a single object, but I could be wrong on this.

Edited by Bacterius

Share on other sites
That sort of thing can't be detected at compile-time, in the general case.
Consider:
void foo(int x)
{
int *p;
if ((x % 2) == 0)
p = NULL;
else if ((x % 3) == 0)
p = new int(0);
else if ((x % 5) == 0)
p = new int[2];

if ((x % 7) == 0)
delete p;
else if ((x % 11) == 0)
delete[] p;
}
This will produce well-defined behaviour if I pass in say 4, 14, 21, 22, or 55, but will produce undefined behaviour if I pass in say 7, 33 or 35, and will leak memory if I pass in say 3. Edited by iMalc

Share on other sites

the delete[] will call the object's destructor function

Share on other sites

i use new[ ] and delete [ ] when i need to  create and delete an allocated array

Edited by ISDCaptain01

Share on other sites

The only difference between delete and delete[] is, that in the latter case the object destructor isn't called for the pointer address only but all subsequent "positions" in the array until the end of the memory block is reached. In theory it should be save to always call delete[] since the memory block would have only sizeof(object). But it's better to follow the rules to ensure compiler compability. You should also consider using dynamic arrays like std::vector which does the gritty things for you.

1. 1
2. 2
Rutin
20
3. 3
khawk
16
4. 4
A4L
14
5. 5

• 11
• 16
• 26
• 10
• 11
• Forum Statistics

• Total Topics
633756
• Total Posts
3013707
×