Heap and stack - understanding memory allocation

Unfortunately this is a concept that unless a programmer has experience with Assembly or C programming it’s unlikely to been a concept that one has learned.

What and where are the stack and heap? .

Each thread of execution in a program has a stack. Our CPUs have the ability to push and pop information off the stack.

When a function is called in a low level language we are pushing the parameters of the function on to the stack which can then be used by the function.

If function is calling another function, which calls another one then each time we pushing more and more data on to the stack. If we push too much we get a “stack overflow”. A stack is like it implies - it is- last in, first out.

When we exit a function the parameters have to be pushed off the stack.

Some low level languages like C support the concept of “stack variables”. These are variables which have their memory allocated on the stack. They only exist in the context of where are created and within sub function calls - but once we exit the “scope” or the function they were created in then they disappear.

See C stack variables.

The heap on the other hand is where most languages like Java, Python etc. allocate memory for their variables and where C uses the malloc api call and C++ uses the “new” operator which is really just calling malloc under the hood.

 

Related pages