Static VS Dynamic memory allocation
- Static memory allocation
- Allocation is done beofre the program's execution
- There is no memory reusability and the memory allocated cannot be freed.
- Less efficient
- Dynamic memory allocation
- Allocation is done during the program's execution
- There is memory resuability and the allocated memroy can be freed when not required.
- More efficient
When we have to make complex program we use dynamic memory allocation and while makeing simple program we use static memory allocation.
How memory is allocated in C programs
Memory assigned to a program in a typical architecture can be broken down into four segments:
- Code
- Also known as text segment
- Static/global variables
- data segment → initialized storage - initializing a global variable and giving value to it. Ex- int a= 2;
- bss(block started by symbol) segment → uninitialized segment- only declared. Ex- int a;
- stack
- It grows as the program goes ahead
- Heap
- It grows as dynamically memory is allocated
- And using of heap is called dynamic memory allocation
C program: Memory layout
Static/global variables
Code
STACK
The function goes in stack as LIFO → last in first out
until a funtion will return value or do something(print value) it remains in stack and pops out after completing its task.
HEAP
If stack and heap meet each other that means we have exhausted the memory and it will do stack overflow. ??
C Program: Stack Overflow
- Complier allocates some space for the stack part of the memory
- When this space gets exhausted for some bad reason, the situation is called as stack overflow
- Typical example includes recursion with wrong/no base condition.
C Program: Heap
- There are a lot of limitations of stack (static memroy allocation)
- Some of the examples include variable sized array, freeing memory no longer required etc.
- Heap can be used flexibly by the programmer as per his needs.
Use of Heap
- We can create a pointer in our main function and point to a memory block in the heap
- The address is stored by the local variable in the main function.
- The memory consumed will not get freed automatically in case we overwrite the pointer
Code
If we write [ gcc filename.c ; size .\a.exe ] → this gives size in bytes of different thing inside the program