A strong answer
When the operating system loads an ELF executable into a process's 64-bit virtual address space, it organizes memory into distinct segments with hardware-enforced page table permissions (R, W, X):
.text(Read + Execute): Contains the compiled machine code instructions of your functions. Marked non-writable so bugs or attackers cannot overwrite instructions..rodata(Read-Only): Holds string literals ("hello") andconstglobal tables. Attempting to write to a pointer aimed at.rodata(char *s = "hello"; s[0] = 'H';) triggers an immediate MMU write fault (SIGSEGV), whereaschar s[] = "hello";copies those 6 bytes onto the writable stack..data(Read + Write): Stores global andstaticvariables that have explicit non-zero compile-time initializers (int max_conns = 1024;)..bss(Read + Write, zero-backed): Holds uninitialized or zero-initialized global andstaticvariables (static char buf[10485760];). On disk,.bssstores only a size number in the ELF header rather than 10 MB of zero bytes; at load time, the kernel maps anonymous zero pages on demand.- Heap (Read + Write, grows upward): Managed dynamically at runtime by
mallocandfreeviabrk/sbrkandmmap. - Stack (Read + Write, Non-Executable, grows downward): Holds function call frames, return addresses, and local automatic variables.
What the interviewer is listening for
- Accurately places functions, string literals, initialized globals, uninitialized globals, heap allocations, and local variables into their exact segments.
- Explains hardware page permissions (
R-Xfor.text,R--for.rodata,RW-for.data/.bss/heap/stack) and why.rodatacauses string literal mutation to segfault. - Explains why
.bsstakes zero disk space in the binary file.
Common mistakes
- Thinking
char *s = "hello"allocates a writable string on the stack or heap (the pointersis on the stack, but the 6 bytes of"hello"sit in read-only.rodata). - Assuming two processes that print the same virtual address (e.g.,
0x401140) are sharing physical RAM without Copy-on-Write or shared mappings—virtual addresses are translated per process by the CPU's MMU and page tables.