stack memory and heap memory | SoloLearn: Learn to code for FREE!


stack memory and heap memory

What is the difference between stack memory and heap memory?

9/15/2020 7:31:55 PM


3 Answers

New Answer


When we talk about the memory layout of a C program there are a number of common sections involved: Text Section - where the code goes Data Section - where initialised variables go BSS Section - where uninitialised variables go Heap - used to provide memory for dynamically allocated variables Stack Section - used to pass arguments to functions, hold local variables, stores cpu registers between functions as required. As a C programmer most of this is taken care of by the compiler and linker so you don't need to think about it. If you create embedded C programs you may need to get very intimate with these concepts if you have to write your own linker scripts.


• • • • Stack is a linear data structure whereas Heap is a hierarchical data structure. Stack variables can't be resized whereas Heap variables can be resized. Stack memory is allocated in a contiguous block whereas Heap memory is allocated in any random order. ©


Stack memory is used for local variables and the function callstack. Recall that stack traces look like this: from main.c 679:23 in main() from main.c 677:5 in foo() from main.c 238:3 in bar() Whenever a function is called, the return address is placed at the top of the stack. When a function returns, the program removes and jumps to the instruction stored at the top of the stack. Heap memory is used for all dynamic memory allocation. The details of dynamic memory allocation are somewhat implementation dependant, but in short, dynamic memory allocation is used to implement arrays and hashes/maps/hashmaps/associative arrays.