----- Original Message -----
From: <am*********@gmail.com>
Newsgroups: comp.lang.c++
Sent: Saturday, July 02, 2005 2:26 PM
Subject: Confuse with local char*
i have a function as listed below:
char* ltoa(char* chr)
{
char* myChr=new char[100];
strcpy(myChr,chr);
return myChr;
}
in the above code i am returning a reference or pointer to a local
variable. Still how come i am getting the expected string in the caller
function of this function. It should print some junk characters. Now ,
I know memory for "myChr" has been allocated from heap. Now, if that is
the reason why I am getting the desired string then how can I allocate
some memory for this "myChr" in local stack so that I get junk chars
when I print the returned string in my caller function of ltoa()?
Actually, you never called delete on myChr. That's why it survives.
Basically the memory that myChr is pointing to is going to survive
until you call delete on it.
Now, if you did:
char myChr[100];
strcpy(myChr,chr);
return myChr;
the memory myChr is pointing to would be cleaned up as soon as
the function line ended.
That is (using my code, not yours):
std::cout << ltoa("Test") << std::endl;
would print Test.
char* temp = ltoa("Test");
std::cout << temp << std::endl;
would probably print junk.
But with your new allocation, either would print "Test".