Typical memory layout of a C program has the following sections:
- Text or code segment - Text segment contains the program i.e., the executable instructions.
- Data segments - Data segments contain initialised and uninitialized global and static variables respectively.
- Stack segment - Stack segment is used to store all local or automatic variables. When we pass arguments to a function, they are kept in stack.
- Heap segment - Heap segment is used to store dynamically allocated variables.
Static variables
- Static variables are stored in the data segment, not in the stack.
- The data segment is active during the entire life-time of program.
- So, static variables preserve their values even after they are out of their scope.
Global variables
- A global variable is declared outside all functions.
- It can be read or updated by all functions.
Dynamic memory allocation functions
C provides dynamic memory management functions in stdlib.h
malloc()
- Allocated requested number of bytes of contiguous memory from the Heap.
- Returns a pointer to the first byte of the allocated space.
- If the memory allocation fails, then
malloc()returns aNULLpointer.
Memory leak
If memory allocated using malloc() is not free()-ed, then the system will “leak memory”. Consequences of memory leak would be:
- Memory leak slowdown system performance by reducing the amount of available memory.
- In modern operating systems, memory used by an application is released when the application terminates.
- Memory leak will cause serious issues on resource-constrained embedded devices.