Dynamic memory allocation within a function
mike r (1)
Oct 14, 2012 at 10:28am UTC
If I have a function that returns a dynamically allocated c-style string, what is the proper way to free this memory?
codewalker (159)
Oct 14, 2012 at 11:46am UTC
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)
Peter87 (3691)
Oct 14, 2012 at 1:30pm UTC
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.
Raman009 (124)
Oct 14, 2012 at 4:15pm UTC
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.
Peter87 (3691)
Oct 14, 2012 at 4:45pm UTC
@Raman009
That quote is about calling delete on the same pointer twice, which is a totally different issue.
vlad from moscow (3112)
Oct 14, 2012 at 4:48pm UTC
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;
}
Raman009 (124)
Oct 16, 2012 at 5:24pm UTC
@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 UTC
Peter87 (3691)
Oct 16, 2012 at 6:12pm UTC
@Raman009
In that case it's not a problem.
Topic archived. No new replies allowed.