Dynamic memory allocation within a function

Oct 14, 2012 at 10:28am
If I have a function that returns a dynamically allocated c-style string, what is the proper way to free this memory?


Oct 14, 2012 at 11:46am
If you used new then use delete, if you used malloc (shouldn't in a C++ program) use free. You might want to check if the pointer is null before calling delete (or free)
Oct 14, 2012 at 1:30pm
You might want to check if the pointer is null before calling delete (or free)

It's not necessary. Using delete or free on a null pointer does nothing.
Oct 14, 2012 at 4:15pm
C++ faq says it makes a lot of difference.

That second delete line might do some really bad things to you. It might, depending on the phase of the moon, corrupt your heap, crash your program, make arbitrary and bizarre changes to objects that are already out there on the heap, etc.
Oct 14, 2012 at 4:45pm
@Raman009
That quote is about calling delete on the same pointer twice, which is a totally different issue.
Oct 14, 2012 at 4:48pm
You have to use operator delete []. For example

1
2
3
4
5
6
7
8
char * f() { return new char[10]; }

int main()
{
   char *p = f();

   delete [] p;
}
Oct 16, 2012 at 5:24pm
@Peter87
If the pointer is assigned null after the delete , will it make difference ?

1
2
3
4
delete ptr ; //first delete
ptr = 0; // now it is null

delete ptr ; //second delete 
Last edited on Oct 16, 2012 at 5:24pm
Oct 16, 2012 at 6:12pm
@Raman009
In that case it's not a problem.
Topic archived. No new replies allowed.