views:

90

answers:

1

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?

+11  A: 

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.

Borealid
Thanks for the reply. I also realized that to be more specific, the memory that is allocated for pn (the space holding this pointer's address data) IS discarded, which is why its contents must be returned to the calling function to make use of it. The memory pointed to by pn was allocated dynamically, and acts according to what you answered.
soula