Search topics...
C / C++ ConceptsMemory Layoutfoundational

What are the memory sections in a C program, and what goes where?

0 upvotes
Practice with AISoon

A typical embedded C program has these memory sections:

  1. .text — compiled machine instructions, placed in flash (read-only).
  2. .rodataconst globals, string literals, and lookup tables, also in flash.
  3. .data — global and static variables with nonzero initializers. Their initial values are stored in flash and copied to RAM at boot by the C runtime.
  4. .bss — global and static variables that are zero-initialized or have no explicit initializer. Zeroed at boot by the C runtime. No flash storage needed for values — only the section size.
  5. Stack — local variables, function arguments, and return addresses. Grows downward from the top of RAM. Size is fixed at link time.
  6. Heap — dynamically allocated memory (malloc/free). Grows upward. Many embedded systems avoid it entirely.

The critical interview point: only .data and .bss are initialized by the startup code. Local (stack) variables are NOT initialized — they contain whatever garbage was in that memory location. This is why int sum; for(...) sum += x; is a bug.

Source: C / C++ Concepts Q&A