|
-
April 27th, 2009, 11:02 AM
#16
Re: return function
@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.
-
April 27th, 2009, 11:09 AM
#17
Re: return function
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.
-
April 27th, 2009, 12:13 PM
#18
Re: return function
wait. str is getting the returning value of function2. So now the value is stored. Why it is cleared when it is printeD?
-
April 27th, 2009, 12:17 PM
#19
Re: return function
 Originally Posted by StGuru
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.
-
April 27th, 2009, 12:18 PM
#20
Re: return function
 Originally Posted by StGuru
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!
Victor Nijegorodov
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|