Re: Returning (char *) from a function - memory problem
Jason wrote:
I don't know if anyone caught my previous post about a project I've
inherited, but I have another question about it.
(Quick summary:
I have old C code, converting to C++. Compiles and runs fine)
My problem is when the application exits, CodeGuard tells me that I
have memory leaks, and points to a function.
char *fooFunc(int Bar)
{
char *returnArr = new char[8];
int stuff;
// do some stuff with Bar
sprintf(returnArr,"%2d",stuff);
return(returnArr);
}
I see that I am allocating memory, but it's not being freed. The
function is called like so:
fprintf(filePtr,"%s and stuff",fooFunc(myInt));
How do I free (delete) the memory allocated by this? I know I could
change it to
char returnArr[8];
You could, but then you'd be returning a pointer to a local variable
which is a VERY BAD THING(tm).
but that would prevent me from learning anything new today.
Not only that, it would have UB.
Let's leave 'new[]' in for now. There is no good way to free that
memory unless you actually store the pointer you obtain from the
function and then use 'delete[]' on that pointer.
You *could* declare 'returnArr' _static_ in that function, but then
you have a multithreading disaster.
It is much better to return a 'std::string':
std::string fooFunc(int Bar) {
std::string returnStr;
...
return returnStr;
}
of course the places where it's called need to be rewritten as well:
fprintf(filePtr, "%s and stuff", fooFunc(myInt).c_str());
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask