Reputation: 400
Assuming I have code like this:
char* Complex::getString(void)
{
char *p;
int n = snprintf( NULL, 0, "%.6f+%.6fi", (float)_re, (float)_im);
p = (char*)malloc(n+1);
sprintf( p, "%.6f+%.6fi", (float)_re, (float)_im);
return p;
}
Should I free p, and if yes - where and why?
Upvotes: 0
Views: 154
Reputation: 26164
In C++ you should rather change signature of your function to return std:string
:
std::string Complex::getString(void);
And your problem is gone.
Instead of snprintf
use std::stringstream
.
If you want to use malloc
, which is not recommended in a C++ program in any case, then obviously the responsibility for releasing the memory is with the caller. Your function cannot release the memory allocated for your string before returning it to the caller. You should document this so users know they have to do. But users of your code (including yourself) will often forget about it and memory will leak. Also, the client code gets more convoluted in this case, which is not great.
Upvotes: 2
Reputation: 254431
If you're writing C With Classes, then you'll have to document that the caller is responsible for freeing the memory. It can't be freed within this function, since you're returning a pointer to it.
If you're writing C++, then life's too short for messing around with raw pointers. Return a std::string
so that the memory is managed automatically.
Upvotes: 10
Reputation: 4695
You should free the pointer returned by the function Complex::getString in the function caller code, when you don't need no more that pointer.
Upvotes: 1
Reputation: 19232
If you malloc
something you should consider freeing it, otherwise you have a leak.
Where? Well, not inside the function since the return value will be no use to the caller. The caller will have to take control of the pointer and free it when they are finished. This will make it hard to write exception safe code.
Of course, if you changed the function signature to return a std::string
you would avoid all these questions/problems.
Upvotes: 3