Typical memory layout of a C program has the following sections:

  1. Text or code segment - Text segment contains the program i.e., the executable instructions.
  2. Data segments - Data segments contain initialised and uninitialized global and static variables respectively.
  3. 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.
  4. 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()

  1. Allocated requested number of bytes of contiguous memory from the Heap.
  2. Returns a pointer to the first byte of the allocated space.
  3. If the memory allocation fails, then malloc() returns a NULL pointer.

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.