Stack and Heap

note from this video

Memory layout

The memory assigned to a program in typical architecture has 4 segments:

  • instruction
    • static/global variables
    • function calls and local variables
    • Heap

Let me show an example of program execution:

Stack

there are memory reserved as stack and memory reserved as static or global variable section:

when the program start executing, the main function is invoked, some amount of memory from the stack is allocated for execution of main. This memory allocation also called the stack frame for the method main(). all the local variables, arguments and the information where this function should return to is stored in the stack frame.

The size of the stack frame for a method is calculated when the program is compiling.

the int total is in the global allocation.

when the SquareOfSum is called, a new stack frame for method squareofsum is allocated. And when Sq() is called, a new stack frame is allocated for Sq()

at anytime during the execution of the program, the function at the top of the stack is executing, the rest is paused to wait the function on top of the stack returns something.

during compiling, the OS allocation certain amount memory for stack, but the actually stack frame is allocated during the runtime, if the actually allocation of stack frame exceeds the allocation size at the compiling time, there will be stack overflow.

The limitation of the stack memory:

  • it is static that is allocated during compiling, not able to change during runtime
  • need to follow the set rule: allocation on top of the stack, and pop up from the top of the stack.

Heap

is used for allocating large chunks of memory, keeping variables till the time we want, or allocating the size of the memory dynamically.

there is no set rule for allocation or deallocation of the memory. programmer can control how long the data will be kept in memory.

heap is also a data structure. but here it is only related to the memory allocation. it is not a data structure here.

malloc will allocate 4 bytes on heap and return a void pointer to the address of that allocated heap.

what is a void pointer?
A void pointer (void*) is a pointer that points to memory without any type information.

How to use the void pointer?
you cast it into a type.
int* p = (int*) malloc(sizeof(int));

now the stack frame of main() store the pointer P, point to heap

change the address of a pointer, should free the memory first– call free()

if malloc is not able to find memory block, it will return null.

c++

In C++

Casting is required:

int* p = (int*) malloc(sizeof(int));  // required in C++

But in modern C++, you should NOT use malloc at all.

Instead:

auto p = std::make_unique<int>();

(or new, though unique_ptr is preferred)

Leave a Reply

Your email address will not be published. Required fields are marked *