Mail Archives: djgpp/1998/07/09/16:13:38
> x = new char[15];
>
> Should I then, when I come to free the memory, use:
>
> delete x;
> or
> delete [] x;
You should use delete [] x, but for obscure reasons. Here's some
background.
The difference between delete and delete [] can be best described by
this example:
#include <stdio.h>
class Foo
{
public:
~Foo() { printf("~Foo!\n"); };
};
int main(void)
{
Foo *foo1 = new Foo[5];
Foo *foo2 = new Foo[5];
printf("delete foo1\n");
delete foo1;
printf("delete [] foo2\n");
delete [] foo2;
return 0;
}
In both cases, an array of objects is created. However, only in the
delete [] case will all the destructors be called.
The obscure part is that some compilers manage this by allocating an
additional bit of memory to keep track of the number of objects in the
array, and free this memory in delete []. If you call delete instead
of delete[], that memory is never freed and you have a memory leak.
- Raw text -