Reputation: 139
I am reading the following code in C++ Primer book:
#include <iostream>
#include <cstring> // or string.h
using namespace std;
char * getname(void); // function prototype
int main()
{
char * name; // create pointer but no storage
name = getname(); // assign address of string to name
cout << name << “ at “ << (int *) name << “\n”;
delete [] name; // memory freed
name = getname(); // reuse freed memory
cout << name << “ at “ << (int *) name << “\n”;
delete [] name; // memory freed again
return 0;
}
char * getname() // return pointer to new string
{
char temp[80]; // temporary storage
cout << “Enter last name: “;
cin >> temp;
char * pn = new char[strlen(temp) + 1];
strcpy(pn, temp); // copy string into smaller space
return pn; // temp lost when function ends
}
What happens with the pointer 'pn' after the return of the function 'getname' ? the memory allocation is not deleted, isn't it supposed to cause a problem?
Upvotes: 1
Views: 102
Reputation: 31290
Let me try to explain it this way. You have a paper note (abbr. pn). You ask a contractor to build you a house on Memory Lane. The contractor builds it (new char[...]
') and tells you, "Oh, it's on no. 4711." Which you duly note on the slip called pn
. All this happens, while you've been called by your wife (The Main Person), and now you tell her, "It*s on Memory Lane, no. 4711", whereafter you throw the paper away and decide to go home. Meanwhile, your wife looks at the house, decides she doesn't like it, and instructs another contractor to destroy that house (delete[] name
), the number of which she has recorded on a slip of paper called name
. ...
Upvotes: 0
Reputation: 42944
What happens with the pointer 'pn' after the return of the function 'getname' ?
The pointer value (which basically is a memory address) is simply copied at the call site, e.g.:
char * name; // create pointer but no storage name = getname()
The value of pn
(i.e. the memory address) returned by getname()
is copied to name
.
the memory allocation is not deleted, isn't it supposed to cause a problem?
Actually, I read some delete[]
lines in the code you posted. So it seems to me that the memory is actually released.
Of course, this code is quite strange: maybe it's for some learning purpose? Is it meant to teach something?
In modern C++ production code, you should just use a convenient RAII string class like std::string
to store and manage your strings.
Upvotes: 1
Reputation: 1641
You're returning a pointer to a block of memory. That block of memory is what is allocated with new. 'pn' itself is destroyed, just like any other automatic variable, but the address it held is returned from getname. The allocated memory still exists until delete is called in the main function. Since delete is called on the allocated memory, no memory leak occurs. You don't lose the pointer because its returned from getname and then assigned in main.
Upvotes: 1