Advertisement

What's difference between stack and heap?

Started by September 10, 2002 04:02 PM
14 comments, last by Big Sassy 22 years, 3 months ago
What is the difference between the stack and the heap? I know that the stack is used when a variable is created without new and the heap is used when a variable is created with new. But why does each operation store the variables in different places? Is it just two different places to store data in memory? Is one more efficient to use then the other? I''m guessing that the stack automatically takes care of it''s data whereas the heap you have to cleanup the data yourself. I know this has probably come up many times before, but the search is down. ***********************           
actually you''re a bit off...
all variables, whether they''re ''new''d or not are created
on the heap. they''re only created on the stack if they''re
global or external.
as to the difference between heap and stack memory i dont
really know.. just thought i''d clarify that little bit

-eldee
;another space monkey;
[ Forced Evolution Studios ]

::evolve::

-eldee;another space monkey;[ Forced Evolution Studios ]
Advertisement
I think also your stack size is fixed, while the heap can grow as big as it wants.
quote: Original post by eldee
actually you're a bit off...
all variables, whether they're 'new'd or not are created
on the heap. they're only created on the stack if they're
global or external.
as to the difference between heap and stack memory i dont
really know.. just thought i'd clarify that little bit

-eldee


That's, um, completely wrong. In fact, it's more or less opposite to the truth.

The "stack" is where variables that are local to a function are created. The reason for this is simple. At any time, one function will be calling another function will be calling another function etc., up until the function that is actually executing. What happens is that each function puts its own local variables on the top of the stack, above all the other previously created functions. When it's done, it takes them off (well, okay, it moves the stack pointer; but it has the same effect) and the previous function continues.

The "heap" is everywhere else in memory that the program can put stuff. It's used to create amounts of memory that don't start and end with functions. Global variables are usually created on the bottom of the stack, but are also sometimes created on the heap; it's really architecture dependent. Maybe someone else can clear this up. Since the global variables last through the entire program, it doesn't really matter where they are.

The heap is most useful for dynamic allocation. For instance, if you make a dynamic array of, say, 20 ints, you don't know when you begin the function that you'll need 80 bytes for it. So the space you get on the heap doesn't allow for it. Instead, when you need the memory, you simply go ask the OS "give me 80 bytes" and the OS says "okay, use the 80 bytes located [here]". Then your program does that.

So, to sum up: stack == function-local variables
heap == dynamically allocated variables

EDIT: Xai's explanation, below, is a lot better than mine.

Don't listen to me. I've had too much coffee.

[edited by - sneftel on September 11, 2002 2:35:04 AM]
Local variables exist on the stack. Global and static variables exist on the heap, along with any memory allocated by ''new'' or ''malloc''.
eldee is DEAD WRONG ...

THE STACK ... is the stack .. in the processor, there are 2 primary pointers, the instruction pointer, and the stack pointer ... every time an intruction is executed the IP is incremented, and the next instruction pocessed .. if that instruction is a jump, the IP is set to a different location (think IF statement, or GOTO) ... the stack pointer is moved every time the program creates a local (BY DEFINITION THIS MEANS STACK) variable, each new local variable is placed on top of the last one in the stack, and when the local variable goes out of scope, the stack pointer is moved back up, effectivly freeing the variable (without any real work) .. the next local variable will simply overwrite the local used by the last one. When a function is called, both the IP and SP are modified, the current IP is put on the stack, then function parameters are put on the stack, and then the IP is changed to the adress of the function. The function uses the variables on the stack to do it''s processing, then when it is done it places it''s return value in a register, pops the parameters off the stack, and reads the return address from the stack and places it into the IP (thereby returning control to the calling function) ...

NOWHERE IN THERE WAS A HEAP USED ....

a heap is an chunk (or often many chunks) of memory, which the application manages using a memory manager (malloc, free, new, delete, Java''s garbage collector, etc) ... these chunks are NOT moved around or invalidated when functions are called and jumps are made, they are only lost when given back to the OS. Basically, the OS has a function for giving a program large blocks of memory (often 4K or so), and the program then allocates these blocks into little ints, floats, strings, and structs ... as needed, through calling allocation / dealocation routines) ...

a global variable is a lot LIKE an item on the heap, in that it''s address doesn''t move, and it isn''t automatically manipulated by instructions and function calls, BUT if you print out the addresses of your local, heap, and global variables, you will likely find their address are partitioned (the min max address of each group do not overlap) ...
Advertisement
Normally 4 (+1) places where variables can live...

Stack: local (non-static) variables only. Locals will be uninitialised (i.e. garbage) on entry to a function (unless initialised in the code)
Heap/free store: used for new/malloc. Zero initialised to begin with, but recycling of heap memory means it won''t stay that way for very long
BSS: Block store section for globals which aren''t initialised in the code, not physically stored in your exe, because as soon as the program executes the whole BSS section is memset to zero
Data: Initialised globals go here, their initial values are stored inside the executable (hence not like the BSS). Initialised local statics go here too.
Bonus area...
Registers: the register keyword can sometimes be used to put local variables in registers. But the compiler can ignore that if it wants. Obviously you can''t take the address of a register variable!

Have a look at the .map which is produced by a compile... tells you which section variables are in.

"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley
"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley
Thanks Xai, Paradigm Shifter, and Sneftel. I have a few more questions:

1) Xai, you said that the stack pointer is in the processor (along with the instruction pointer). Does that mean that the stack data is stored on the processor? Or does that mean that the stack pointer merely points to the location of the stack in memory?

2) What exactly is a register?

3) Just for clarity''s sake, when you call new/malloc the program will request a chunk of memory from the OS. It will then divy out that chunk of memory to each subsequent call to new/malloc until it uses up that chunk. When that happens, it asks the OS for another chunk of memory and the process start all over again. Correct?

4) If that is correct, does the program give each chunk of memory back to the OS when every bit of that chunk of memory has been freed (delete/free)?

5) If your thinking "I wish this guy would just RTFM", do you have any book suggestions?

***********************
          
1) The stack is in ram, but the esp register (I''m talking x86 processors here) is in the CPU, which is a pointer to the current stack position (in the RAM).

2) A register is RAM that is inside the CPU chip. It''s the fastest memory you can have, but you only have a few of them.

3 & 4) It depends on the implementation of malloc or new and on the operating system, which is in charge of the RAM.

5) Try a book on x86 ASM for more info on registers etc. Don''t know where I learnt about the section stuff, probably debugging!

"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley
"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley
The stack is not actually located in the CPU, it''s in the RAM (or cache I don''t know) and the SP register, which itself is in the CPU, refers to the location in RAM where the last stack value is written/to be stores.

Registers are little pieces of CPU-speed RAM (the fastest you''ll ever get ) the CPU calculates. If for instance you would do " a += a; " where a is an int, the CPU would load a from wherever in RAM it is into a register, increment it, and put it back.

Hope that helps (and is correct).

This topic is closed to new replies.

Advertisement