Why is the allocated pointer memory stored after the function, but not the array?

So, I ask this question in the context of the main text input function that 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 characters, an automatic variable whose memory will be freed after getString() returns. It was recommended that if for some reason you returned temp , using it outside the function would not be reliable, as this memory was freed after the function terminated. But since I also declare pn in the same context, why is its memory also not discarded?

+4
source share
1 answer

Because objects declared with new are allocated on the heap, while variables of type temp are on the stack.

When your function returns, its stack stack is freed, but the heap is not affected.

+11
source

All Articles