new and delete[]

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?
Hi

try
delete buffer;
or
delete(buffer);

hope this helps
Shredded
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?
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
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.