Memory Layout Flashcards
Text Section
Program Code
Data Section
Stores global and static data
Heap
Heap is an area of ram memory where dynamic memory allocation happens. It grows upwards and has holes.
Stack
Stack is where function related data is stored: local variables, saved registers, return addresses, function parameters
Grows down.
Is there a single text, data, heap sections for all running programs or does each program has its own sections?
each one has its own. The same is somewhat true for stack because stacks are never shared)
What do we mean by “stack is fast, heap is slow”? What exact operations on stack are faster than on heap?
memory allocation, that is finding chunk of unused memory of required size
stack is very fast because mem is managed automatically.
Where is the local object of std::vector class or std::string class is stored?
the object itself on stack, the pointed dynamically allocated array – on heap
vector<int> vec = {1, 2, 3, 4, 5}; // Local object</int>
// vec's metadata (size, capacity, pointer to data) is on the stack. // The array {1, 2, 3, 4, 5} is stored on the heap.
static array
int nums[100];
Dynamic array
A dynamic array is an array whose size is determined at runtime.
std::vector<int> nums;</int>
What is between heap and stack section?
unused memory chuncks happen in the middle of heap but not stack
What unit fits best for a usual stack size limit: kB, MB, GB
sually stack size limit is measured in MB, something like 8 MB to 32 MB depending on the system
What is stack overflow?
When the program tried to exceed stack size limit and the program crashes
What are the two common ways to overflow the stack?
large static arrays and deep recursion
What is the mechanism of stack overflow by the deep recursion?
Every time a function is called, a new stack frame is pushed onto the call stack.
The stack frame contains:
Local variables of the function.
Function parameters.
Return address to the caller function.
Be ready to look at C++ code and analyze in what sections all of its components are stored.
PRACTICE