What a C programmer should know about memory logo

What a C programmer should know about memory

Free

Practical memory management for C programmers

FreeFree tier
Type
Open Source

About What a C programmer should know about memory

A detailed blog post by Marek Vavrusa that explains practical aspects of memory management for C programmers. It covers virtual memory, process memory layout, overcommit, demand paging, and other core concepts, building upon Ulrich Drepper's famous article. Written with a focus on Linux and C99, but many topics are universal. Aimed at bridging theoretical knowledge with everyday programming practices.

Key Features

Explains virtual memory and address spaces
Covers process memory layout (stack, heap, MMS)
Discusses memory overcommit and its implications
Includes demand paging explanation
Provides practical tips for malloc and null checks
Focuses on Linux with C99 examples but applicable broadly

Pros & Cons

Pros
  • Practical, hands-on explanations
  • Builds on well-known foundational article
  • Covers both theory and real-world implications
  • Written by experienced systems programmer
  • Includes platform-specific details for Linux
Cons
  • Limited to Linux and C99; Windows not covered
  • Assumes prior familiarity with basic C programming
  • Article is not comprehensive; focuses on key concepts
  • Some sections assume knowledge of x86-64 architecture

Best For

Learning memory management for C programmingUnderstanding virtual memory conceptsImproving low-level system programming skillsReference for Linux memory layout specifics

FAQ

What is virtual memory and why is it important?
Virtual memory gives each process its own address space, providing isolation and the ability to use more memory than physically available via mapping (backing with physical memory or storage). It's fundamental to modern OS protected mode.
Why might malloc return a non-NULL pointer even when memory is insufficient?
Because of overcommit: the OS may give a valid pointer to memory it doesn't actually have. The memory is only allocated when accessed, possibly leading to an OOM killer terminating the process.
What is the process memory layout on Linux?
The layout includes segments like text, data, heap, memory mapping segment (MMS), and stack. The MMS typically grows downward from a randomized address below the stack, but can also grow upward if the stack limit is large/unlimited.