It makes absolutely no difference what function3() does. None. It can do anything. The point is, the act of calling it overwrites whatever was on the stack below main(), which will wipe out the data function2() had put in its local "test" variable (if it isn't gone already) and demonstrates the problem.
str is getting the returning value of function2. So now the value is stored. Why it is cleared when it is printeD?
Lindley is taking advantage of something implementation dependent, i.e., it is an attempt to trigger the use of the memory previously allocated to the destroyed array. This attempt happens to work.
Really, just keep it simple: do not return a pointer to an object that will be destroyed when the function returns. It is as simple as that, even if by chance you find that it works.
C + C++ Compiler: MinGW port of GCC
Build + Version Control System: SCons + Bazaar
wait. str is getting the returning value of function2. So now the value is stored. Why it is cleared when it is printeD?
This "value" is a pointer to some memory location where a character array was placed before function2 has returned. And at the time you are printing this memory was reallocated and reoccupied by some other data!
Bookmarks