Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a pointer's allocated memory persist after a function, but not an array?

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?

like image 287
soula Avatar asked Dec 22 '22 00:12

soula


1 Answers

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.

like image 66
Borealid Avatar answered May 18 '23 19:05

Borealid