Stack memory is a special region of your computer’s memory that stores temporary variables created by each function (including the main()
function). The stack is a “FILO” (first in, last out) data structure, that is managed and optimized by the CPU quite closely. Every time a function declares a new variable, it is “pushed” onto the stack. Then every time a function exits, all of the variables pushed onto the stack by that function, are freed (that is to say, they are deleted). Once a stack variable is freed, that region of memory becomes available for other stack variables.
The heap is a region of your computer’s memory that is not managed automatically for you, and is not as tightly managed by the CPU. It is a more free-floating region of memory (and is larger). To allocate memory on the heap, you must use malloc()
or calloc()
, which are built-in C functions. Once you have allocated memory on the heap, you are responsible for using free()
to deallocate that memory once you don’t need it any more. If you fail to do this, your program will have what is known as a memory leak. That is, memory on the heap will still be set aside (and won’t be available to other processes). This can lead to a slower PC, as there isn’t as much memory for other processes.
by JBuildz17
http://forum.brackeys.com/thread/what-are-the-differences-between-stack-and-heap-memory-allocation-c/