The function cannot return a pointer to the stack memory! Because the return is a copy of the value!
Char *str = "ABCD" is a string constant, this can be returned, and char str[] = "ABCD" cannot be returned in the function, because this is a local variable, and the memory is freed after the function is finished.
If you do not want to return local variables, you can only use static to limit the local variables, so that the function will not release the memory of the variable after the end.
or use the new command to request space in the called function, and then use Delete to free up space after the call is finished, but the disadvantage is that the interface is unfriendly.
Here are four case studies
1. Correct. The most normal situation. int returnvalue (); int _tmain (int argc, _tchar* argv[]) { Std::cout<<returnvalue (); return 0; } char returnvalue () { int value=3; return value; &n BSP;} 2. Error. The most normal error. While value is freed, its value is not necessarily erased, so sometimes you use it to look as if the result is right, but the hidden danger is endless. [CPP] int* returnvalue (); int _tmain (int argc, _tchar* argv[]) { std::cout<<* (returnvalue ()); & nbsp; return 0; } int* returnvalue () { int value=3; Return & Value } 3. correct. Not surprisingly, "Hellojacky" is a string constant stored in a read-only data segment, return STR just returns the first address of the string in the read-only data segment, and when the function exits, the memory in which the string resides is not recycled, so it is normal. [Cpp] char* returnvalue (); int _tmain (int argc, _tchar* argv[]) { Std::cout<<returnvalue (); return 0; } char* returnvalue () { char* str= "Hellojacky"; return str ; } 4. Error. This time "Hellojacky" is a local variable inside the stack, the memory is freed when the function exits, so the address of the local variable inside the stack is wrong. [CPP] char* returnvalue (); int _tmain (int argc, _tchar* argv[]) { Std::cout<<returnvalue (); return 0; } char* returnvalue () { char str[]= "hellojacky"; return str; }
Memory considerations for functions in C + +