stack and heap

Discussion in 'C Programming' started by Spiros Bousbouras, Jun 26, 2007.

  1. On 26 Jun, 22:02, "Roman Mashak" <> wrote:
    > Hello,
    >
    > I'm confused about heap and stack memories management in C language.


    C language (as specified by the standard) doesn't say anything
    about stack or heap and their management. Specific implementations
    might worry about such issues if they are relevant to the platform on
    which they run.

    > Most
    > books explain that local stack variables for each function are automatically
    > allocated when function starts and deallocated when it exits.


    Which books are those ? Do they claim to speak on standard C or
    C on specific operating systems ?

    > In contrast,
    > malloc() always takes memory in the heap.


    When you say always do you mean on every operating system
    on every platform which has a C compiler ? I doubt that this
    is true.

    > Now, let's consider the code as
    > follows:
    >
    > int get_buffer()
    > {
    > unsigned int head; // local variable?
    > char *buf; // also local?


    If by "local" you mean automatic then the answer is yes.
    In other words you won't be able to access the values of
    the variables head and buf after the function exits.

    > char = malloc(100); // allocate memory from heap


    I will assume that you meant to write buf instead of char.
    There are no guarantees that the memory will be allocated
    from the heap or even that such a thing exists on your
    platform.

    > ...
    >
    > }
    >
    > Here is confusion: "char *buf" is supposed to be allocated in stack, on the
    > other hand, malloc() get memory from heap? How to understand this?


    If you happen to be running the above programme on an
    operating system where heap and stack are meaningful
    terms then it is likely that buf will be allocated on the
    stack and buf from the heap. Let's say that a memory segment
    of size of at least 100 bytes is allocated starting at the
    address A000. Then the value A000 will be stored in the
    area of memory allocated for buf. Note that we have 2
    different things here : one is the actual memory which
    starts at the address A000 and the other is the value
    A000 which can be stored somewhere else , perhaps on
    the stack if such a thing exists. In any case for the vast
    majority of C programmes you need not worry whether
    the memory is allocated on the stack or heap or whatever.
    If you think you need to worry then you have probably
    misunderstood something.

    > Is this
    > true, that whenever we call malloc (inside of function or outside), we get
    > memory from heap?


    Unknown. And for most C programmes you needn't worry
    about it.
    Spiros Bousbouras, Jun 26, 2007
    #1
    1. Advertising

  2. On 26 Jun, 06:40, Spiros Bousbouras <> wrote:
    > On 26 Jun, 22:02, "Roman Mashak" <> wrote:
    > > Here is confusion: "char *buf" is supposed to be allocated in stack, on the
    > > other hand, malloc() get memory from heap? How to understand this?

    >
    > If you happen to be running the above programme on an
    > operating system where heap and stack are meaningful
    > terms then it is likely that buf will be allocated on the
    > stack and buf from the heap.


    Arrrggh , I meant to say that buf will be allocated on the stack
    and the area returned by malloc on the heap. But my mistake
    gives some insight on why one might get confused.
    Spiros Bousbouras, Jun 26, 2007
    #2
    1. Advertising

  3. On 26 Jun, 22:02, "Roman Mashak" <> wrote:

    > I'm confused about heap and stack memories management in C language.


    the C standard (the official, definitive definition of the C language)
    doesn't mention "stack" or "heap". It talks about "automatic"
    variables,
    and "dynamic" memory. Automatic variables are created on entry to a
    block
    (a function is a block) and destroyed on exit. Dynamic memory
    is allocated when malloc() (et al) is called and freed when free() (et
    al)
    is called.

    *Some* implemntations use stacks and heaps to implement these things.

    > Most
    > books explain that local stack variables for each function are automatically
    > allocated when function starts and deallocated when it exits.


    most books? Assuming the terminology has been corrected...

    > In contrast,
    > malloc() always takes memory in the heap.


    seems pretty clear to me.

    > Now, let's consider the code as
    > follows:
    >
    > int get_buffer()
    > {
    > unsigned int head; // local variable?
    > char *buf; // also local?



    yes, both local to the function

    >
    > char = malloc(100); // allocate memory from heap
    > ...
    >
    > }
    >
    > Here is confusion: "char *buf" is supposed to be allocated in stack,


    yes...

    > on the
    > other hand, malloc() get memory from heap?


    yes, it does.

    > How to understand this?


    understand what?

    > Is this
    > true, that whenever we call malloc (inside of function or outside), we get
    > memory from heap?


    yes


    buf points to the malloc()ed memory. In many implementations
    the memory on the stack corresponding to buf holds the address
    of the heap memory that has benn malloced


    --
    Nick Keighley
    Nick Keighley, Jun 26, 2007
    #3
  4. Spiros Bousbouras

    pete Guest

    Nick Keighley wrote:
    >
    > On 26 Jun, 22:02, "Roman Mashak" <> wrote:
    >
    > > I'm confused about heap and stack memories management in C language.

    >
    > the C standard (the official, definitive definition of the C language)
    > doesn't mention "stack" or "heap".
    > It talks about "automatic" variables, and "dynamic" memory.


    The standard might talk about "dynamic" memory,
    but the standard calls it "allocated".

    --
    pete
    pete, Jun 26, 2007
    #4
  5. On Jun 26, 2:02 pm, "Roman Mashak" <> wrote:
    >
    > I'm confused about heap and stack memories management in C language.


    The C language doesn't have the concepts of 'stack' and 'heap', it
    just has memory. Particular implementations of C may use one or other
    of these concepts, and most use both.

    > Most
    > books explain that local stack variables for each function are automatically
    > allocated when function starts and deallocated when it exits. In contrast,
    > malloc() always takes memory in the heap.


    That's a fairly common style of implementation, though small automatic
    variables (what you call 'local stack variables') may often get
    allocated to registers and not use any memory at all.

    > Now, let's consider the code as follows:


    OK, and let's assume a simplistic C implementation which uses stack
    and heap as you describe above.

    > int get_buffer()
    > {
    > unsigned int head; // local variable?
    > char *buf; // also local?
    >
    > char = malloc(100); // allocate memory from heap
    > ...
    >
    > }
    >
    > Here is confusion: "char *buf" is supposed to be allocated in stack, on the
    > other hand, malloc() get memory from heap? How to understand this?


    What's to understand? You need to explain what you are confused about.
    'buf' is a pointer which gets placed on the stack (in this particular
    implementation). malloc is a function which allocates memory from the
    heap (in this particular implementation). 'head' and 'buf' are
    accessible for the duration of function get_buffer and can no longer
    be accessed once the function returns. The memory allocated by malloc
    is accessible until you explicitly free it.

    > Is this
    > true, that whenever we call malloc (inside of function or outside), we get
    > memory from heap?


    You get memory from wherever malloc happens to allocate it, and that
    memory is accessible until you explicitly free it.

    It's not clear what you are confused about; if you need more help,
    please post again and try to be more explicit about your confusion.
    J. J. Farrell, Jun 26, 2007
    #5
  6. Spiros Bousbouras

    Roman Mashak Guest

    Hello,

    I'm confused about heap and stack memories management in C language. Most
    books explain that local stack variables for each function are automatically
    allocated when function starts and deallocated when it exits. In contrast,
    malloc() always takes memory in the heap. Now, let's consider the code as
    follows:

    int get_buffer()
    {
    unsigned int head; // local variable?
    char *buf; // also local?

    char = malloc(100); // allocate memory from heap
    ...
    }

    Here is confusion: "char *buf" is supposed to be allocated in stack, on the
    other hand, malloc() get memory from heap? How to understand this? Is this
    true, that whenever we call malloc (inside of function or outside), we get
    memory from heap?

    Thank you.

    --
    Best regards, Roman
    Roman Mashak, Jun 26, 2007
    #6
  7. On Tue, 26 Jun 2007 14:02:47 -0700, in comp.lang.c , "Roman Mashak"
    <> wrote:

    >Hello,
    >
    >I'm confused about heap and stack memories management in C language.


    Its really simple - the C /language/ doesn't require either to exist.
    Specific /implementations/ may well use stacks and heaps (most do) but
    you would need to ask the specialists in your particular compiler for
    details, over in a different group. And its unlikely you really need
    to know anyway.

    >int get_buffer()
    >{
    > unsigned int head; // local variable?
    > char *buf; // also local?


    yes, but you can't say anything about where it is allocated from.

    > char = malloc(100); // allocate memory from heap


    possibly, but again C doesn't require this.

    >Here is confusion: "char *buf" is supposed to be allocated in stack, on the
    >other hand, malloc() get memory from heap? How to understand this? Is this
    >true, that whenever we call malloc (inside of function or outside), we get
    >memory from heap?


    You don't need to know. Seriously. You should just use the correct
    allocation method for the object you need, and let the compiler and OS
    worry about where to get the memory from.
    --
    Mark McIntyre

    "Debugging is twice as hard as writing the code in the first place.
    Therefore, if you write the code as cleverly as possible, you are,
    by definition, not smart enough to debug it."
    --Brian Kernighan
    Mark McIntyre, Jun 26, 2007
    #7
  8. >I'm confused about heap and stack memories management in C language. Most
    >books explain that local stack variables for each function are automatically
    >allocated when function starts and deallocated when it exits. In contrast,
    >malloc() always takes memory in the heap. Now, let's consider the code as
    >follows:
    >
    >int get_buffer()
    >{
    > unsigned int head; // local variable?
    > char *buf; // also local?
    >
    > char = malloc(100); // allocate memory from heap
    > ...
    >}
    >
    >Here is confusion: "char *buf" is supposed to be allocated in stack, on the
    >other hand, malloc() get memory from heap? How to understand this? Is this


    C does not define the terms "stack" and "heap". Some people define
    "heap" as "that place from which malloc() obtains its memory", and
    define "stack" as "that place from which automatic variables are
    allocated". There is no guarantee that *BOTH* places aren't "Fred's
    Used Computer Salvage Yard". On the other hand, there's no reason
    you can't reverse the definitions of the two, although it's a bit
    strange.

    There's a difference between a pointer and what it points to. For
    example, you put a postal address ("pointer to a residence") on an
    envelope. But you cannot fit the actual house on the envelope.
    And it looks pretty strange erecting an address complete with postal
    code on a residential lot.

    The variable "buf" is an automatic variable. The pointer assigned
    to buf points at memory from malloc(), assuming malloc() succeeded.

    >true, that whenever we call malloc (inside of function or outside), we get
    >memory from heap?


    No. If malloc() fails, you don't get any memory from anywhere.

    You can't call malloc() outside of a function.

    The variable to which you assign the pointer returned by malloc()
    is not in memory returned by *that* call to malloc(), although it
    might be in memory from a previous call to malloc() (say, you're
    doing linked lists). There's a difference between a pointer variable
    and what it points to.
    Gordon Burditt, Jun 27, 2007
    #8
  9. Spiros Bousbouras

    user923005 Guest

    On Jun 26, 2:02 pm, "Roman Mashak" <> wrote:
    > Hello,
    >
    > I'm confused about heap and stack memories management in C language. Most
    > books explain that local stack variables for each function are automatically
    > allocated when function starts and deallocated when it exits. In contrast,
    > malloc() always takes memory in the heap. Now, let's consider the code as
    > follows:
    >
    > int get_buffer()
    > {
    > unsigned int head; // local variable?
    > char *buf; // also local?
    >
    > char = malloc(100); // allocate memory from heap
    > ...
    >
    > }
    >
    > Here is confusion: "char *buf" is supposed to be allocated in stack, on the
    > other hand, malloc() get memory from heap? How to understand this? Is this
    > true, that whenever we call malloc (inside of function or outside), we get
    > memory from heap?


    Perhaps you are really asking:
    There are these two cans on the shelf that both say "Memory!" but one
    of them says 'automatic' and the other one says 'allocated'. Now,
    both of those cans have mouth-watering pictures of delicious memory
    tidbits... ready for consumption. Which one to try? Are they both
    the same flavor? Do they have any bad aftertastes? Which one will a
    real memory *connoisseur* choose?

    Both of them are wonderful, both for simple snacks and for the main
    course, but they also have some subtleties that you must be aware of.

    For either one, you can empty the can, and when you reach in for more
    -- too bad! It's empty!! :-(

    Now, what happens when it is empty is not the same. The 'allocated'
    can just comes up empty, and leaves it up to you about what to do with
    the missing ingredient for your recipe. On the other hand, the
    'automatic' can has a mean trick. When you try to pour some out of
    the empty 'automatic' can, razor sharp shards of shredded program
    spill all over the floor. Well then, we'll just use 'allocated' all
    the time. But not so fast... The 'allocated' can has a mean streak
    of its own. You only get to borrow the memory, and if you forget to
    put it back in the can, it can cause all kinds of headaches. Big
    lumps of it start loafing around and annoying the other dishes that
    are being prepared. Before you know it, it fills the whole room like
    some water from the 'Sourceror's Apprentice' and nothing useful can be
    done. Not only that, but if you should forget to check if the can is
    empty, the "gag" address given to you will cause a heinous falling of
    your whole cake, and you'll probably burn the cookies.

    Oh, and when cooking with hot stuff, don't forget the oven mits.
    user923005, Jun 27, 2007
    #9
  10. In article <>,
    Gordon Burditt <> wrote:
    [without attributions - Stop Doing That]

    >>Here is confusion: "char *buf" is supposed to be allocated in stack, on the
    >>other hand, malloc() get memory from heap? How to understand this? Is this

    >
    >C does not define the terms "stack" and "heap". Some people define
    >"heap" as "that place from which malloc() obtains its memory", and
    >define "stack" as "that place from which automatic variables are
    >allocated". There is no guarantee that *BOTH* places aren't "Fred's
    >Used Computer Salvage Yard". On the other hand, there's no reason
    >you can't reverse the definitions of the two, although it's a bit
    >strange.


    There is actually a very good reason not to, at least in one direction:
    Automatic variables behave in the way you'd expect if they were placed
    on a "stack", in the algorithms-and-data-structures sense of the word.
    That is, new automatic variables are created for each new scope[1] entered
    and destroyed when that scope is exited, and no scope can be exited until
    every scope entered after the entry of that one has been exited, so they
    have the last-created, first-destroyed nature that would be expected of
    something called a "stack". Dynamically allocated memory does not have
    this property, and using the term "stack" to describe something without
    this property would make gratuitiously make it much harder for anybody
    to understand you.

    Not coincidentally, the "stack" (in a different sense of the word: a block
    of memory indexed by a register designated by the processor's instruction
    set or by a common convention that is moved incrementally as data is
    added or removed) that many implementations targeting general-purpose
    processors use to store automatic variables behaves in this way, with
    the additional useful feature of being able to look at anything that's
    currently on the stack instead of being restricted to popping the first
    element off (which the algorithms-and-data-structures stack doesn't allow,
    but which is Rather Useful for automatic storage in a C program).


    (The algorithms-and-data-structures "heap" doesn't map as nicely onto
    the properties of mallocated memory, though.)


    dave

    [1] "Scope" is used informally here, meaning approximately "lexical
    block in a unique invocation of a function". So a function calling
    another function (including recursively calling itself) creates a
    new scope, as does entering a block controlled by a loop statement.

    --
    Dave Vandervies
    Shouldn't that be "gedankenmord"? Unless you enjoy getting Germans
    wound up by perverting their language. I sure do.
    --Steve VanDevender in the scary devil monastery
    Dave Vandervies, Jun 27, 2007
    #10
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. joe

    stack and heap question

    joe, Aug 4, 2004, in forum: Java
    Replies:
    3
    Views:
    424
    Michael Borgwardt
    Aug 5, 2004
  2. Steve Hill

    vector.swap and heap / stack

    Steve Hill, Aug 20, 2003, in forum: C++
    Replies:
    5
    Views:
    986
    tom_usenet
    Aug 22, 2003
  3. Michal Slocinski

    Heap dump file size vs heap size

    Michal Slocinski, Mar 25, 2008, in forum: Java
    Replies:
    1
    Views:
    717
    GArlington
    Mar 25, 2008
  4. viki
    Replies:
    6
    Views:
    554
    Erik Wikström
    Jun 28, 2008
  5. Raymond Schanks
    Replies:
    0
    Views:
    496
    Raymond Schanks
    Apr 11, 2010
Loading...

Share This Page