|
-
March 21st, 2003, 07:40 AM
#1
Memory problem
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()?....
-
March 21st, 2003, 07:51 AM
#2
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).
-
March 21st, 2003, 08:28 AM
#3
Sure, the char *pChDup is destroyed when ReturnDub exits, but you may still use the memory it was pointed to freely.
-
March 21st, 2003, 03:24 PM
#4
You can use memmory, becouse
return pChDup;
create copy of pChDup for returning from
function before pChDup local pointer will be destroed.
-
March 21st, 2003, 06:14 PM
#5
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?
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|