Skip to main content

Lesson 7 of 26 · 12 min read

Address spaces and the C memory API

Explore the virtual address space illusion — code, heap, sparse gap, and stack — alongside malloc(), free(), and classic C memory bugs.

Virtual address space components: Virtual text, Dynamic heap, Unmapped gap, and Auto stack.
Each process sees a private linear map of code, heap, sparse gap, and stack backed by virtual memory.
Course syllabus · lesson 7 of 26
In this lesson

A process that executes a load instruction supplies a virtual address. The processor interprets that address using the mapping for the current process, and the operating system decides which regions exist and which operations each region permits. Two processes can both load from 0x2400 and read different values because each has its own map. If the OS deliberately maps the same read-only library code into both processes, the same physical bytes can safely serve both.

Time sharing made this arrangement valuable. Keeping several programs in RAM lets the scheduler switch to a ready process when another blocks for input. Giving each program a private map lets it keep using its pointers after a switch and prevents an ordinary store from modifying a neighbor's memory. The map needs to be transparent to programs, quick enough to consult on every instruction fetch and data access, and restrictive enough to enforce isolation.

An address-space diagram with text at low addresses, followed by heap, an unmapped gap, and stack at high addresses.
Open full-size diagram
Increasing numerical addresses run down this diagram. The heap grows toward higher addresses and the stack grows toward lower addresses.

Trace stack and heap lifetimes

Stack · high addresses new frame, Heap empty, Code · low addressesStack · high addressesnew frameHeapemptyCode · low addresses

Step 1 of 4

Enter a function

A call adds a frame on the stack for local state. In this layout the stack grows toward lower addresses.

Read the map in address order

Consider a 16 KiB teaching address space. Its 14-bit byte addresses run from 0x0000 through 0x3FFF. Use half-open intervals so the end address is excluded and the interval size is simply end minus start. In this example, the lowest range is a guard region.

  • [0x0000, 0x1000) is unmapped. Applications commonly leave low addresses inaccessible to catch accesses through null pointers on the target platform.
  • [0x1000, 0x1800) contains executable text. Text is commonly readable and executable, and shared mappings can let multiple processes use the same code bytes.
  • [0x1800, 0x2000) contains static data. An initialized global has a value supplied by the program image. An object with static storage duration and no explicit initializer starts zero-initialized.
  • [0x2000, 0x2800) is the current heap region. Increasing its upper limit extends it toward higher numerical addresses.
  • [0x2800, 0x3800) is an unmapped gap. Its addresses are part of the numbering scheme and currently have no mapped storage.
  • [0x3800, 0x4000) is the mapped stack. A downward-growing stack extends toward lower numerical addresses as nested calls require space.

These are illustrative region boundaries without a specified page size. In a real paged system, permissions and mappings operate at page granularity. The loader and kernel may add shared libraries, file mappings, separate stacks for threads, and protected gaps around regions. Address-space layout randomization can change placements between runs. The diagram draws increasing addresses toward the bottom, so the heap arrow points down on the page while its numerical addresses increase.

For a byte at 0x2403 the offset into the model heap is 0x2403 - 0x2000 = 0x403. That arithmetic says where the byte sits relative to the start of a virtual region. Finding its physical location requires the current process's mapping. A load from 0x3000 instead reaches the gap and traps in this model. The kernel checks whether the trap describes an allowed event, such as an eligible stack growth on a real system, or an access for which the process has no mapping.

Storage duration and ownership

In C, a local array such as int points[8]; has automatic storage duration. It typically lives in the current stack frame, although the compiler can keep values in registers or omit storage when it can preserve the program's behavior. Each recursive call that needs its own copy has a distinct object. The lifetime ends when control leaves the array's block. Returning a pointer to that local array gives the caller a pointer it cannot use to access the old array.

An object obtained from malloc has allocated storage duration. It can outlive the function that acquired it. The caller needs a convention for ownership because C pointer assignments merely copy addresses. If a function hands back its allocated result, document whether the caller owns the result or borrows it. An owner releases it once. A borrower may access it only during the agreed lifetime. The owner can itself be a data structure that releases every element when the structure is destroyed.

Static storage duration supplies a third lifetime. A global or a function-local static object lives for the execution of the program. A function-local static keeps its value across calls even though its name is only visible in its scope. Scope governs where a name can be written in C source. Storage duration governs how long the associated object exists. A pointer to an automatic local can escape its scope while the local is alive, such as when passed to a helper called within the block.

For a concrete observation, print object pointers with printf("%p\n", (void *)ptr). Compare the address of a global, the address of a local, and the pointer returned by malloc. The output format is implementation-defined and often hexadecimal. The heap pointer names a payload in the allocated region. Taking the address of the pointer variable may instead locate a local stack object that holds that payload address.

Build an allocation from its element count

Suppose a caller needs a dynamically allocated array with count elements. The payload size is count * sizeof *values. Using the pointed-to type makes the size follow the declaration when the element type changes. For a typical four-byte int, ten elements need 40 bytes. On a target with eight-byte pointers, sizeof values would be eight. When a caller passes an array to a function taking a pointer, supply the element count separately.

Code exampleC
#include <stdint.h>
#include <stdlib.h>

int *make_values(size_t count) {
    int *values;

    if (count == 0) {
        return NULL;
    }
    if (count > SIZE_MAX / sizeof *values) {
        return NULL;
    }

    values = malloc(count * sizeof *values);
    if (values == NULL) {
        return NULL;
    }

    for (size_t i = 0; i < count; ++i) {
        values[i] = 0;
    }
    return values;
}

This function defines zero elements as an empty result. For nonzero requests it checks for overflow before multiplying. Because size_t is unsigned, a multiplication beyond SIZE_MAX wraps and can ask the allocator for a small block while the initialization loop still uses the large count. A successful malloc result is suitably aligned for ordinary object types. Its contents require initialization before use. calloc takes the count and element size separately and initializes the allocated bytes to zero. The caller of make_values still checks the result before indexing it and calls free when finished.

Resizing has a separate ownership rule. For a nonzero requested size, save the result of realloc in a temporary. Failure returns NULL and the original allocation remains valid. On success, use the returned pointer and rebuild any pointers into the old block from saved indices or offsets. Newly added bytes have unspecified contents, so initialize them before reading. Handle a desired capacity of zero with an explicit free and reset the owning pointer. The next lesson about allocators explains why a block may have to move when its immediate neighbor is already occupied.

Diagnose mistakes by the rule they break

Consider a short string copy. strlen("map") is three, while the string occupies four bytes including its terminating zero. The broken allocation below needs an extra byte. The indexed loop shows precisely where the overrun happens.

Code exampleC
/* Broken example for inspection. */
const char *src = "map";
size_t len = strlen(src);
char *buf = malloc(len);
if (buf != NULL) {
    for (size_t i = 0; i <= len; ++i) {
        buf[i] = src[i];
    }
    free(buf);
}

With a successful three-byte allocation, indices 0, 1, and 2 hold the letters. The last iteration writes at index 3, one past the allocation. The fix is to allocate len + 1 bytes for the complete string and retain the allocation failure check. Alignment may leave padding in the allocator's chunk, but the C program's permitted extent is still the requested size. A write past that extent has undefined behavior even when it lands inside a mapped, writable page.

  • Uninitialized read. Assigning the first element of a newly allocated array leaves the remaining elements uninitialized. A loop that sums the full array must wait until every element it reads has been set.
  • Leak. If the only owning pointer is overwritten before its block is freed, the allocator still considers the block live, and the program has lost the means to release it. Repetition can raise memory demand even if each iteration's input size stays fixed.
  • Use after free. If alias = buf was saved earlier, free(buf) ends the allocation's lifetime for both names. Resetting buf to NULL helps that owner avoid accidental reuse, while alias must be retired by the ownership convention.
  • Double or invalid free. A second free of the same allocation violates the API contract. The same applies to free(buf + 1) and freeing the address of an automatic object. Return the original allocation pointer exactly once. free(NULL) is allowed.
  • Unchecked failure. A request can exceed the memory the allocator can provide. Check for NULL before copying or dereferencing, and release any previously acquired objects if the enclosing operation gives up.

These failures can be intermittent. The MMU checks the enclosing mapped region and its permissions on an access. It has no per-object information from malloc. A memory checker such as AddressSanitizer can track much finer allocation boundaries and provide the allocation and access sites when it detects a violation.

From library calls to operating-system mappings

The C library typically obtains larger ranges from the kernel and subdivides them. On Unix-like systems, examples include extending the traditional heap through a program-break interface and obtaining anonymous regions with mmap. Requests can often be fulfilled entirely from an arena the allocator already manages. A successful free returns the block to that allocator. The library may keep its containing pages for later requests or return eligible mappings to the kernel.

Three quantities can therefore differ substantially in one process. The virtual map can cover a large range reserved for possible use. Resident memory counts the pages currently in RAM, some of which may be shared. Live allocation size counts the application payloads currently owned through the allocator. If a server frees a large batch of small allocations and its resident memory barely moves, those frees may have made chunks reusable while the allocator retained their pages.

Worked trace of one heap allocation

Take the teaching map above and assume the allocator returns buf = 0x2400 for malloc(4). Follow a copy of "map" and then the block's release.

  1. The allocation owns the range [0x2400, 0x2404). Both endpoints lie within the current heap range, and the payload length is four bytes.
  2. The stores to indices 0 through 3 produce virtual addresses 0x2400, 0x2401, 0x2402, and 0x2403. The fourth byte is zero. The MMU uses the current address space to check and translate each store.
  3. Another process may also own an allocation at 0x2400. The equality of the numbers supplies no evidence that the two stores reach the same physical bytes.
  4. The caller frees buf. A subsequent read through an alias remains invalid at the C level even if the kernel still maps the same page and the old bytes happen to be there.

Change one input. Reduce the allocation request from four bytes to three while keeping the copy loop unchanged. Find the first illegal access. It is the write of the terminator at 0x2403. That byte is exactly the new exclusive endpoint and still inside the writable heap region, so the allocator contract is violated even if the MMU lets the store complete.

Next, follow the same virtual addresses through base-and-bounds relocation and segmentation.

Before you move on

Try it in your workspace

Compile the small C heap/stack snippet and inspect printed virtual addresses. Compare stack growth, heap allocation, code text, and globals, then deliberately introduce one bug and observe it safely.

Keep a short note of what you tried, what passed, and what you still need to check.

Your practice record

0 of 3 checked.

Saved in this browser when storage is available. Uncheck any item to revisit it. This is your own record, not an assessment.