Dynamic memory allocation within a function

If I have a function that returns a dynamically allocated c-style string, what is the proper way to free this memory?


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)
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.
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.
@Raman009
That quote is about calling delete on the same pointer twice, which is a totally different issue.
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;
}
@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
@Raman009
In that case it's not a problem.
Topic archived. No new replies allowed.