Stack vs Heap ??
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 16

Thread: Stack vs Heap ??

  1. #1
    Join Date
    Jul 2005
    Posts
    36

    Stack vs Heap ??

    I have confusion on allocate memory from Stack or Heap?

    Anyone can demonstrate me with some code ?

    which is allocated from Stack and which is from Heap

    thanks : )
    Last edited by dlhc922; July 28th, 2005 at 08:14 PM.

  2. #2
    Join Date
    Jun 2002
    Posts
    1,417

    Re: Stack vs Heap ??

    when you use new or malloc() the memory is normally allocated from the heap. When you allocate an object within a function, it goes on the stack
    Code:
    void foo()
    {
       int x; <<< x is on the stack
      char *ptr = new char[255]; <<< 255 characters are allocated in the heap
                                but ptr object is on the stack 
    
    int array[255]; <<< 255 ints are all on the stack
    }

  3. #3
    Join Date
    Jun 2005
    Location
    The Netherlands
    Posts
    185

    Re: Stack vs Heap ??

    Quote Originally Posted by stober
    when you use new or malloc() the memory is normally allocated from the heap. When you allocate an object within a function, it goes on the stack
    Code:
    void foo()
    {
       int x; <<< x is on the stack
      char *ptr = new char[255]; <<< 255 characters are allocated in the heap
                                but ptr object is on the stack 
    
    int array[255]; <<< 255 ints are all on the stack
    }
    so whats the difrence?

  4. #4
    Join Date
    Oct 2002
    Location
    Singapore
    Posts
    3,128

    Re: Stack vs Heap ??

    The difference can be identified from the usage of the operator new. When it is used, you will be allocating memory from the heap and you need a pointer to store the address. As the memory from the stack, the variable has to be declared within a function without using operator new.

  5. #5
    Join Date
    Jun 2002
    Posts
    1,417

  6. #6
    Join Date
    Feb 2004
    Location
    where Eurasian, Pacific and Philippine tectonic plates meet
    Posts
    229

    Re: Stack vs Heap ??

    ...provided that you know what is the stack and what is the heap...
    "Such ingratitude after all the times I saved your life." (imdb quotes)
    A bit of history.

  7. #7
    Join Date
    Jun 2002
    Posts
    1,417

    Re: Stack vs Heap ??

    Quote Originally Posted by Mercantilum
    ...provided that you know what is the stack and what is the heap...
    If not, then look those terms up in any of the hundreds of text books at your local book store or library. You can even find the definitions in Websters online dictionery http://dictionary.reference.com/search?q=heap

  8. #8
    John E is offline Elite Member Power Poster
    Join Date
    Apr 2001
    Location
    Manchester, England
    Posts
    4,242

    Re: Stack vs Heap ??

    You can imagine the stack as being like a stack of plates. As soon as a function calls some other function things get added to the stack (from the bottom, upwards) starting with the return address (i.e. where the program flow should go back to, once the called function has finished).

    Stack memory
    Let's suppose there was nothing on the stack to begin with. One of the functions (either the calling function or the called function) would start a stack by placing a return address - and some extra 'plates' might be added, representing any arguments that get passed to the called function (the called function's parameters).

    Program execution then gets passed to the called function which probably adds some more plates in the form of 'local variables'. Every 'plate' has some sort of information written on it that means something special to te program. By the time the called function reaches its return statement it has a big stack of plates. Just before it returns, it removes the plates (one by one) from the top downward so that it can read the return address, written on that very bottom plate. The program then jumps back to that original return address.

    The most important thing about the stack is that you don't need to think much about it. Your program manages it. Also, stack management is very efficient because the plates don't literally need to be removed (like they would if they were real plates). In reality, the program contains a "stack pointer" that simply gets updated each time a particular plate needs to be written to or read from. The size of the stack is usually quite small because it's mostly used for local variables (variables that go out of scope pretty soon after they're finished with). The size of the stack is set at compile time and is small enough to be available on any computer, no matter how little RAM it's got.

    Heap memory
    The heap is a different thing altogether. Different PC's have different amounts of memory so it would be silly to have to allocate all the memory at compile time. If a particular computer has a lot of RAM, why not make use of it? Therefore the heap consists of memory that can be allocated at run time. The amount of heap memory is different for different machines and a well written program will take account of this (allocating heap memory sparingly - and not assuming that everyone will have massive amounts of it). Heap memory is most often used for 'large' things (e.g. the contents of a file) - or for things that need to 'stay around' in memory so that different functions can share the data (in other words, for NON-local variables). It's also used very frequently to allocate memory for things whose size is not known until run time. For example, if you had to open a file and read in the data, you don't know how much data exists until run time. In contrast, the size of objects allocated on the stack, needs to be known at compile time.

    Whereas your program takes care of stack memory (allocating it & cleaning it up) it's the programmer's job to deal with heap memory. The size of objects allocated on the heap is often not known to the compiler - therefore the programmer must allocate and release the memory specifically.
    Last edited by John E; July 29th, 2005 at 02:01 AM.
    "A problem well stated is a problem half solved. - Charles F. Kettering

  9. #9
    Join Date
    Jul 2005
    Posts
    12

    Re: Stack vs Heap ??

    The most difference between the stack and heap is you must manage the variable which allocate the memory from the heap -- allocate and callback--and the variable which allocate the memory from the stack will be allocated the memory by machine

  10. #10
    Join Date
    Feb 2005
    Location
    "The Capital"
    Posts
    5,306

    Re: Stack vs Heap ??

    Quote Originally Posted by Kheun
    The difference can be identified from the usage of the operator new. When it is used, you will be allocating memory from the heap and you need a pointer to store the address. As the memory from the stack, the variable has to be declared within a function without using operator new.
    ...and calling the constructor too as it happens. Heap is be to totally your resposibility. What you allocate on to it, is your responsibility to be deleted once you are done with it. Else you get into a condition know as memory leaks which could be very un-healthy for you. Try allocations on stack as much as possible...on heap? only when you need it and u are sure of what you are doing.

  11. #11
    Join Date
    Oct 2002
    Location
    Germany
    Posts
    6,205

    Wink Re: Stack vs Heap ??

    The Stack is a Hardware Supported Feature in terms of Microprocessor Registers and Segments.

    The Heap is actually a Software Abstraction.

    For more information on the Stack, read this thread.

    Also, on a side note - when one allocates using "new" one allocates on the Free Store.
    Often, the Free Store is implemented as the "heap".

    For more information on Free Store, Stack and Heap, please read this article.

  12. #12
    Join Date
    Jan 2009
    Posts
    2

    Re: Stack vs Heap ??

    Here is a sample code:

    class A()
    {
    private:
    int i;
    char c;
    public:
    A();
    };

    void fun(A* a)
    {
    a = new A(); //allocated on heap(2nd time allocation)
    }
    int main()
    {
    A a; // allocated on stack
    fun(&a);
    }

    Stack is where variables declared before runtime are stored.

    Heap is where variables created or initialized at runtime are stored.

    Here is another good site I found about heap and stack

    What is heap and stack

    Any more questions?

  13. #13
    Join Date
    Mar 2002
    Location
    NY, USA
    Posts
    12,097

    Re: Stack vs Heap ??

    Quote Originally Posted by xjessie007 View Post
    Any more questions?
    Only three...

    1) Why to you think the persion is waiting for an answer after 3.5 YEARS?
    2) Why have you not enabled Private messaging as recommented in the "BEFORE you post announcement"
    3) Why are you posting code without using code tags (as covered in the same referrecced material)?
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009
    In theory, there is no difference between theory and paractice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

  14. #14
    Join Date
    Jan 2009
    Posts
    2

    Re: Stack vs Heap ??

    sorry, I have not looked at the timestamps on the posts.

    I haven't searched through the forum on how to enable private messaging, this functionality is usually enabled by default, so I haven't expected that it would be off by default or that someone would want to contact me righ away.

    I do not see code tags here. As I am writing this post, there are no icons above this edit text box. (?)

  15. #15
    Join Date
    May 2011
    Posts
    2

    Re: Stack vs Heap ??

    Great answer to this question, with more details:

    http://www.programmerinterview.com/i...tack-and-heap/

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center