Re: Memory location of bytes

From: James Dennett (jdennett_at_acm.org)
Date: 07/25/04


Date: Sun, 25 Jul 2004 14:06:58 -0700

Ben Measures wrote:
> Edo wrote:
>
>> Hello
>> the code below puts out -4, I was expecting 4, could some one explain
>> why?
>>
>> x1 is [snip] the lower number, x2 [snip] is [the] bigger number.
>
>
> A positive number minus a larger positive number will have a negative
> result. O_o
>

Note also that there are no guarantees in C or C++ about the
relative addresses in memory of local variables; it's quite
legal for them to be allocated in multiple frames which could
in turn be dynamically allocated.

For even more fun, note that simply taking their addresses can
change things: often when the use of two variables don't actually
overlap, optimizing compilers can use the same memory for both
of them (or sometimes not place them in memory at all) unless
your code "observes" the addresses, in which case the compiler
is more constrained.

It's interesting and informative experimentation to look at
things like stack addresses to see some examples of what can
happen and how things can be done, but it's important not to
conclude that the behaviour you observe is guaranteed.

-- James



Relevant Pages

  • Re: when to use "new"
    ... Maybe you should understand what the stack is and what the heap is. ... the memory for local variables are ...
    (comp.lang.cpp)
  • Re: Problems with Scope of aliased Objects
    ... memory space on the stack, which it uses for local variables. ... "new" to allocate heap-memory dynamically. ...
    (comp.lang.ada)
  • Re: Intel Mac and Snowleopard simple pascal?
    ... That certainly is not what my memory of ancient FORTRANs is. ... Dynamic allocation of local variables has always been allowed, ... have long been some compilers that did it, ... Compiler support of recursive procedures as an extension was getting ...
    (comp.sys.mac.system)
  • Re: Deallocating Local Variable used by Malloc
    ... A conforming C compiler may not compile the above line. ... char *ret_buf; ... Also dynamically allocated memory persists even after execution ... Also returning local variables may cause ...
    (comp.lang.c)
  • Re: Why this code is working
    ... > But when a function returns, the compiler reclaims all the memory ... > assigend to the local variables. ... "Reply" at the bottom of the article headers. ...
    (comp.lang.c)