new and delete[]

Dec 21, 2010 at 7:47pm
I want to free memory which I dynamically allocated with this:
char * buffer = new char[size];
I tried deallocating it with this:
delete[] buffer;
But I get a segmentation fault. I don't try to access that memory after I free it. What's going on?
Dec 21, 2010 at 8:15pm
Hi

try
delete buffer;
or
delete(buffer);

hope this helps
Shredded
Dec 21, 2010 at 9:19pm
I was freeing it in my destructor and in a method so I was trying to free the memory twice.
But thanks anyways Shredded.
and would
delete buffer;
or
delete (buffer);
deallocate the entire array or just the pointer?
Dec 21, 2010 at 9:34pm
Well, the standard says you should use
delete[]
to remove stuff created with
new[]
so lets stick to that. The other way, using just a
delete
might (or might not) work.

Cheers
Dec 22, 2010 at 7:59am
nick85 wrote:
I was freeing it in my destructor and in a method so I was trying to free the memory twice.
Never forget to initialze your pointer with null bofore new and after delete. And always check the pointer for null then

I find it a good question why delete[] should be used. It's not because of the amount of memory (it's known in both cases). It's because of calling the destructor for each element. In your case you don't have a destructor but follow what ernestus said.

The sad thing about that is: In case of dynamic memory management C++ knows the the size and the number of elements but doesn't reveal it to the programmer, or is there a legal way I just don't know?
Topic archived. No new replies allowed.