So, I ask this question in the context of a basic text input function I see in a C++ book:
char *getString()
{
char temp[80];
cin >> temp;
char * pn = new char[strlen(temp + 1)];
strcpy(pn, temp);
return pn;
}
So temp declares an array of 80 chars, an automatic variable whose memory will be freed once getString()
returns. It was advised that if you returned temp
for some reason, its usage outside of the function would not be reliable since that memory was freed once the function finished. But since I'm also declaring pn
in the same context, how come its memory is not also discarded?
Because objects you declare with new
are allocated on the heap, while variables like temp
are on the stack.
When your function returns, its stack frame is deallocated, but the heap is not affected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With