Click to See Complete Forum and Search --> : Memory problem


SunnyPriya
March 21st, 2003, 06:40 AM
What is the significance of memory in the following code:
consider function
// code begin
char* ReturnDup(const char* pChOrg)
{
char* pChDup;
pChDup = new char[strlen(pChOrg)+1];
strcpy(pChDup,pChOrg);
return pChDup;
}
// code over
suppose main program uses this function, like
// code begin
...
...
char* pChFun;
pChFun = ReturnDup("Life is wonderful");
cout << pChFun << endl;
...
...
...
// code over
what ever memory we have allocated is in function ReturnDup, doesnt it remain local in the function ReturnDup?
how can we use the return value in main()?....

Gabriel Fleseriu
March 21st, 2003, 06:51 AM
No, it doesn't. The char * pChDup is a local variable. It will be destroyed when the function exits but the memory it points to will remain allocated until you delete[] it.
(ok, a char * is a built in, it does not have a dtor -- the term "destroyed" may be inappropiate).

brapler
March 21st, 2003, 07:28 AM
Sure, the char *pChDup is destroyed when ReturnDub exits, but you may still use the memory it was pointed to freely.

Alex Rest
March 21st, 2003, 02:24 PM
You can use memmory, becouse
return pChDup;
create copy of pChDup for returning from
function before pChDup local pointer will be destroed.

Tweaks
March 21st, 2003, 05:14 PM
Sunny,

Variables declared locally, such as
int x; string MyString;
-- these are deleted when they go out of scope, such as when the function returns.
These are put on the stack, and are fast.

However, memory *allocated* using new and delete are NOT deleted when the go out of scope. For example, the program

int main()
{
char * mine;
mine = new char[500];
}

creates a memory leak, because the memory allocated is never deleted.
Memory allocated with new stays good until it's deleted, so it can be used anywhere in the program as long as you have the pointer to it.

Does this help at all?