Possible Duplicate:
Can a local variable’s memory be accessed outside its scope?
I’ve declared a C style array using pointer, and assign it a value returned by a function.
1.const char* str = chArr->readString();
Right after above, I want to cout the str as follow:
2.cout << "pointer to char is = " << str <<endl;
and the readString is:
char* CharArray::readString()
{
std::cout << "Insert a string of max 19 length:" <<std::endl;
char string[20];
std::cin.getline(string,20,'\n');
return string;
}
When I put a break point on line 2, I can see the correct result as value of str.
But the console window shows nothing, and after passing step 2, when I look at the str value, it shows something like “P÷7” or “äû:“,..
Maybe worth saying that for the str I strings with length of 4,5. Not 19 despite the length of str.
You are returning a pointer to a local variable. The memory address of this variable is made available again by the system after the function ends. So it is possible that some other code overwrites it with some random data and that’s why you are seeing gibberish.
In order to safely do this, use:
char* string = new char[20];Remember to
delete []it afterwards.