@Lindley thanks for the code, but I do not understand what the function3 does?
@VictorN now it prints random string, but again I don't know what's the difference with the code of laserlight.
Printable View
@Lindley thanks for the code, but I do not understand what the function3 does?
@VictorN now it prints random string, but again I don't know what's the difference with the code of laserlight.
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.
wait. 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.Quote:
Originally Posted by StGuru
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.
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!Quote:
Originally Posted by StGuru