First, a piece of code:
#include <stdio.h> #include <tchar.h>char* test (void) {char arr[] = "hello,world\n";//arr[] All elements are stored on stack memory, arr is a symbolic address, no storage space return arr;//warning C4172: Returns the address of a local variable or temporary variable/that is, the warning returns a pointer to the stack memory, returns the stack memory will be automatically reclaimed}int _tmain (int argc, _tchar* Argv[]) {printf ("%s", Test ()),//print out garbage data, or just print out "hello,world, depending on how the compiler handles stack memory reclamation GetChar (); return 0;}
The code runs normally without any errors, but there is a warning
Warning 1 Warning C4172: Returns the address of a local variable or temporary variable main.cpp 7 1 consoleapptest
When the function returns, the local variable and the temporary object are destroyed, so the address returned is invalid. You need to modify the code so that it does not return the address of the local object.
So how to solve? How do I change the code?
The following is from (slightly modified): http://hi.baidu.com/dotcloud/item/302c4414f7f30e5f2b3e222c
Example of the above party code
Method 1:
#include <stdio.h> #include <tchar.h>char* test (void) {char *arr = "hello,world\n";//"hello,world\n" Save in read-only constant area, non-stack memory is not affected by function return return arr;//actually returns a copy of Arr, returned after the ARR variable is also sold, but its point to the constant area is unaffected}int _tmain (int argc, _tchar* argv[]) {printf ("%s", Test ());//can print out Hello,worldgetchar (); return 0;}
Method 2:
#include <stdio.h> #include <tchar.h>char* test (void) {static char arr[] = "hello,world\n";//"hello,world\n "Stored in static storage, non-stack memory is not affected by function return. Return arr;//with Method 1 arr is a symbolic address, no storage space}int _tmain (int argc, _tchar* argv[]) {printf ("%s", Test ());//can print out Hello,worldgetchar (); return 0;}
Warning about a C + + function returning a local variable