Re: Returning a reference to a local variable
On 2007-12-30 09:43, Dreamlax wrote:
>> Thanks, Peter. You seem to have put a lot of time and effort towards
>> ing me and I appreciate that. However, I'm still a bit confused.
>> I understand why your example code is bugged. The mystery (to me) is
>> why the code I posted originally _does not_ appear to suffer from the
>> reference-to-local bug. It works on my compiler, and was copied from
>> what seemed like a decent website.
>>
>> Paul Epstein
>
> I think on most systems, when a program is compiled, its size reflects
> the number of local variables declared in the code. For example, if a
> long integer required 4 bytes, then the program's compiled code will
> increase by 4 bytes for every long integer (and then rounded to the
> nearest 16k block or whatever). This is because the entire program is
> loaded into memory at once. After it is loaded into memory, local (and
> global) variables now become addressable places in memory. If the
> compiler is very smart, and knows that the code is not multithreaded,
> it may use the same 4 bytes as the local integer variable in two
> separate functions just to save on filesize. Therefore, the reference
> returned by one function may point to a place in memory that can be
> changed through another local variable in another function. The
> contents of the memory addressed by the return value of that function
> cannot be guaranteed to be constant throughout the remainder of the
> execution of the program.
No. Local variables are (usually, I sure there exists exceptions) placed
on the stack, which is allocated on runtime. When a function is called a
new stackframe, which is big enough to contain all local variables of
the function, is pushed onto the stack. When the function exits the
frame is poped of the stack. But the memory used is left as it was, this
means that as long as no new frame is pushed onto the stack and over-
writes the memory the values will still be readable. This does not mean
that one should try to be smart and try to "utilise" this, it will only
lead to ruin.
--
Erik Wikström
|