An understanding of memory layout in C – Part 1

This article tries to discuss the basics of memory layouts in C.  When a C file is preprocessed, compiled, assembled and linked – a memory layout of the code/data/stack/heap area is generated. The C program memory layout is depicted below

FIG COURTESY:https://en.wikipedia.org/wiki/File:Program_memory_layout.pdf

The different sections are

  • .text segment – code section – the C code is placed here. The .text segment contains executable instructions and is shareable across multiple instances of the program. It is a read-only segment.
  • .data segment – initialized data – the global/static/constant initialized variables are placed here. It is a read-write memory.
  • .bss segment – uninitialized data – the global/static/constant uninitialized variables are placed here. It is also a read-write memory.
  • .heap segment – dynamically allocated memory region. Memory allocated via malloc/calloc/kalloc etc.
  • .stack segment – automatic variables/variables passed in functions are stored in stack

Note: The basic notion is that stack and Heap grow in opposite directions, usually the assumption is that stack grows downwards and Heap grows upwards. When both stack and heap meet – program runs out of memory. 

Though the above comment is universally accepted, stack can also grow upwards and heap downwards in memory and is actually platform dependent.

 

Understanding Memory Layout in C – Part 2

Leave a Reply

Your email address will not be published. Required fields are marked *