Programming Search⌘K

Conceptcore

Manual memory management

Also called manual memory management, explicit memory management, malloc and free, dynamic memory allocation.

The program asks an allocator for a block of memory and later gives it back with an explicit call. The programmer decides when each block is freed, and the language does not check it.

Applies to
core-languages

Idea

A program often needs memory whose size or lifetime it knows only at run time. Examples are a list of orders from a file, a message buffer and a growing tree. Such memory cannot live in a stack frame, because the frame ends when the function returns. The program asks an allocator for a block from the heap instead. With manual memory management, the program also gives the block back with an explicit call. Nothing frees the block for it.

C has four storage durations: static, thread, automatic and allocated. Allocated storage lives from the call that allocates it to the call that frees it.1 In the C program below, malloc returns a block for four int values, or a null pointer when it has no memory. The program checks the result, uses the block, and frees it.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    size_t count = 4;
    int *totals = malloc(count * sizeof *totals);
    if (totals == NULL) {
        return 1;
    }
    for (size_t i = 0; i < count; i++) {
        totals[i] = (int)(i * 10);
    }
    printf("last total: %d\n", totals[count - 1]);
    free(totals);
    return 0;
}
Output
last total: 30

The model gives the programmer full control and full responsibility. The language does not track which pointer owns a block. A block that is never freed is a leak. A block that is freed twice, or used after it is freed, is undefined behaviour.1 Garbage collection, reference counting and ownership types are the other answers to the same question: who frees this block, and when?

How it works

The C library has a small set of functions for allocated storage.1

Function What it does
malloc(size) returns a block of size bytes; the contents are indeterminate
calloc(n, size) returns a block for n objects of size bytes, all bits zero; it returns a null pointer if n * size does not fit in a size_t
realloc(ptr, size) returns a block of size bytes with the old contents up to the smaller size; the block can move
aligned_alloc(align, size) as malloc, with a stated alignment
free(ptr) gives the block back; free(NULL) does nothing
free_sized(ptr, size) as free, and the caller also passes the size it asked for

Each function returns a null pointer when it cannot allocate the memory. The program must check for it, or it risks a NULL pointer dereference.13 The C standard does not say where the blocks are, or in what order they come.1 Calling free on a pointer that the allocator did not return, or on a block that is already free, is undefined behaviour.1 The rationale states the rule plainly. Free only what you allocated, free it only once, and do not touch it after the free.2

In C++, a new expression calls an allocation function and then runs the constructor. A delete expression runs the destructor and then calls the deallocation function. The default operator new returns a valid pointer or throws std::bad_alloc; it never returns null. The std::nothrow forms return null instead.4 The array forms are separate. new T[n] must be paired with delete[], and new T with delete; any other pairing is undefined behaviour.3

The allocator

The allocator is ordinary library code. It gets large regions from the operating system and cuts them into blocks. Each block starts with a header that stores at least its size, so that free needs only the pointer. A free block also holds the links of a free list in its own payload, so the list costs no extra memory.1718

            header        payload
block A   | size 32 | in use: order          |
block B   | size 48 | free: next -> D        |
block C   | size 32 | in use: user           |
block D   | size 64 | free: next -> (end)    |
top       | the rest of the region, not yet cut into blocks |

free list: B -> D

The pseudocode shows a first-fit allocator, the method of the Seventh Edition Unix malloc.19 MALLOC takes the first free block that is large enough and splits off the rest. FREE merges the block with free neighbours, which is called coalescing.18

  1. MALLOC(n)
  2. 1size ← n plus the header, rounded up to the alignment
  3. 2for each block b on the free list do ▷ first fit
  4. 3if size(b) ≥ size then
  5. 4if size(b) − size ≥ the minimum block then split b; put the rest on the free list
  6. 5remove b from the free list; return the payload of b
  7. 6cut size bytes from the top, or ask the operating system for more
  8. 7if the operating system refuses then return null
  9. FREE(p)
  10. 8if p = null then return
  11. 9b ← the block whose payload starts at p ▷ the header is before p
  12. 10if the next block is free then merge it into b
  13. 11if the previous block is free then merge b into it ▷ needs a size at the end of each block
  14. 12put b on the free list

Line L11 needs the size of the previous block. Knuth's boundary tags store the size in a footer at the end of each block as well as in the header.18 Real allocators add more structure. glibc keeps chunks in bins by size class and keeps a small cache of free chunks per thread (tcache). It also gives groups of threads separate arenas to reduce lock contention.17 Some of its small bins (fastbins) are not coalesced at all, so a free is faster but memory stays split.17 Very large requests go directly to mmap, and their free returns the memory to the operating system at once.16 Most other freed memory stays in the free lists, so a process rarely gets smaller after free.14

Fragmentation is the price of this design. Internal fragmentation is memory inside a block that the program did not ask for, from rounding and headers. External fragmentation is free memory split into pieces that are too small for the requests that come.18 C cannot move a live block to close the gaps, because the program holds raw addresses.18 A compacting garbage collector can move blocks; a C allocator cannot.

Ownership conventions

The language does not record who frees a block, so the program must state it. Each function that returns or takes a pointer needs one of three contracts:

  • The caller frees. The function allocates and returns the block, and the caller must free it. cgo documents C.CString this way: the string is in the C heap, and the caller must call C.free.31
  • The callee keeps it. The function borrows the pointer and does not free it.
  • Ownership moves. The function takes the block and frees it later. Rust makes this explicit: Box::into_raw makes the caller responsible for the memory, and Box::from_raw takes the responsibility back.25

Libraries often pair the functions: order_create and order_destroy, each documented in the header. The C++ Core Guidelines treat a raw pointer T* as non-owning (R.3). They forbid the transfer of ownership through a raw pointer (I.11). When the owner is in doubt, the result is a leak or an early destruction.56 Where a raw owning pointer is necessary, the guidelines mark it as owner<T*>.5

In languages

LanguageVerdictNote
PythonAbsentThe Python memory manager owns the private heap of all objects, and a program has no operation that frees an object. Alternative: A C extension allocates and frees raw memory with PyMem_Malloc and PyMem_Free.
C++Native
JavaStandard library
CNative
C#Standard library
JavaScriptAbsentThe language has no operation that frees an object; the engine collects objects that the program can no longer reach.
TypeScriptAbsentThe same as JavaScript; the type system adds no free operation.
GoAbsentThe garbage collector frees all memory, and the language has no free operation. Alternative: Cgo can call C.malloc and C.free, outside the rules of standard Go.
RustStandard library
KotlinStandard libraryKotlin/Native allocates with nativeHeap.alloc and frees with nativeHeap.free in kotlinx.cinterop, and Kotlin/JVM can use the Java Arena; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applyThe database engine manages storage, and a query has no access to raw memory.
BashDoes not applyThe shell manages its own strings and arrays, and a script has no access to raw memory.
PowerShellStandard libraryA script can call the .NET methods Marshal.AllocHGlobal and Marshal.FreeHGlobal, as the C# example does; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyMarkup has no memory to manage; the DOM belongs to the JavaScript engine.
CSSDoes not applyStyle rules have no memory to manage.
Regular expressionsDoes not applyA pattern has no memory to manage.
Language Verdict How a program frees memory by hand
C native malloc, calloc, realloc, aligned_alloc and free1
C++ native new and delete, new[] and delete[], plus the C functions34
Rust stdlib std::alloc::alloc and dealloc with a Layout, in unsafe code; Box::into_raw and Box::from_raw232425
C# stdlib Marshal.AllocHGlobal and Marshal.FreeHGlobal; NativeMemory.Alloc and NativeMemory.Free in unsafe code2627
Java stdlib Arena.ofConfined() allocates memory outside the heap; close() frees all of it28
Kotlin stdlib Kotlin/Native: nativeHeap.alloc and nativeHeap.free; on the JVM, the Java Arena33
PowerShell stdlib the .NET Marshal methods, as in C#
Go absent the garbage collector frees all memory; cgo can call C.malloc and C.free3031
Python absent the Python memory manager owns the private heap; C extensions use PyMem_Malloc and PyMem_Free32
JavaScript absent no operation frees an object; the engine collects it
TypeScript absent as JavaScript
Bash n/a the shell manages its own strings and arrays
SQL n/a the database engine manages storage
Regex n/a a pattern has no memory to manage
HTML/CSS n/a markup and style have no memory to manage

C and C++ are the languages where manual management is the base model. C++ adds constructors and destructors to the same idea, so a new expression gives an initialized object and not raw bytes. The Core Guidelines advise against malloc and free in C++ (R.10), and against explicit new and delete in application code (R.11). They prefer owners such as std::unique_ptr and containers that free their memory in a destructor.78 This is the subject of Resource acquisition is initialization.

Rust normally frees memory through ownership: a value is dropped when its owner goes out of scope (see Ownership and borrowing). The std::alloc functions expose the global allocator for code that builds its own containers. The call to dealloc must pass the same Layout that alloc received, and both calls need unsafe.2324

C# and Java run on a garbage-collected heap, so the manual APIs are for memory outside that heap, mostly for calls into native code. .NET describes AllocHGlobal as a legacy API and points to NativeMemory.26 The Java Arena frees a group of segments at once. A confined arena belongs to one thread, and an access after close throws IllegalStateException.28

Go, Python, JavaScript and TypeScript give the program no free operation. The Go FAQ calls memory management by hand in C a frequent cause of bugs, and Go uses garbage collection alone.30 In Python, the user has no control over the private heap.32 Go and Python can still reach a C allocator through cgo or a C extension, but then the C rules apply.

#include <memory>
#include <print>
#include <string>

struct User {
    std::string name;
    explicit User(std::string n) : name(std::move(n)) { std::println("construct {}", name); }
    ~User() { std::println("destroy {}", name); }
};

int main() {
    User* admin = new User("admin");     // allocate, then construct
    std::println("hello, {}", admin->name);
    delete admin;                        // destroy, then deallocate

    int* totals = new int[3]{10, 20, 30};
    std::println("last total: {}", totals[2]);
    delete[] totals;                     // the array form matches new[]

    auto guest = std::make_unique<User>("guest");
    std::println("hello, {}", guest->name);
}                                        // unique_ptr deletes guest here
Output
construct admin
hello, admin
destroy admin
last total: 30
construct guest
hello, guest
destroy guest
  • Verdict: native. A new expression allocates memory and runs a constructor, and a delete expression runs the destructor and frees the memory.
  • new[] must be paired with delete[], and new with delete. Any other pairing is undefined behaviour.
  • std::make_unique makes an owner that calls delete in its destructor. The output shows guest destroyed at the end of main without an explicit delete.
  • The default operator new throws std::bad_alloc on failure, so the program does not check for a null pointer.
JavaGitHub
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;

public class Main {
    public static void main(String[] args) {
        try (Arena arena = Arena.ofConfined()) {
            MemorySegment totals = arena.allocate(ValueLayout.JAVA_INT, 4);
            for (int i = 0; i < 4; i++) {
                totals.setAtIndex(ValueLayout.JAVA_INT, i, i * 10);
            }
            System.out.println("last total: " + totals.getAtIndex(ValueLayout.JAVA_INT, 3));
        } // close() frees every segment of the arena
        System.out.println("arena closed");
    }
}
Output
last total: 30
arena closed

This code raises IllegalStateException, on purpose.

import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;

public class Main {
    public static void main(String[] args) {
        Arena arena = Arena.ofConfined();
        MemorySegment totals = arena.allocate(ValueLayout.JAVA_INT, 4);
        arena.close();
        System.out.println(totals.getAtIndex(ValueLayout.JAVA_INT, 0));
    }
}
  • Verdict: stdlib. The Foreign Function and Memory API allocates memory outside the Java heap, and Arena.close() frees it.
  • An arena frees all its segments at once, so the program frees a group of blocks and not each block.
  • After close, an access to a segment throws IllegalStateException. In C the same mistake is a use after free with undefined behaviour.
  • A confined arena belongs to the thread that made it. Arena.ofShared() makes an arena that several threads can use and close.
#include <stdio.h>
#include <stdlib.h>

struct order_list {
    int *ids;
    size_t count;
    size_t capacity;
};

// The caller owns the result and frees it with order_list_destroy.
struct order_list *order_list_create(void) {
    struct order_list *list = calloc(1, sizeof *list);
    return list;
}

// Returns 0 on success; on failure the list is unchanged.
int order_list_add(struct order_list *list, int id) {
    if (list->count == list->capacity) {
        size_t capacity = list->capacity == 0 ? 2 : list->capacity * 2;
        int *ids = realloc(list->ids, capacity * sizeof *ids);
        if (ids == NULL) {
            return -1;
        }
        list->ids = ids;
        list->capacity = capacity;
    }
    list->ids[list->count++] = id;
    return 0;
}

void order_list_destroy(struct order_list *list) {
    if (list != NULL) {
        free(list->ids);
        free(list);
    }
}

int main(void) {
    struct order_list *list = order_list_create();
    if (list == NULL) {
        return 1;
    }
    for (int id = 100; id < 105; id++) {
        if (order_list_add(list, id) != 0) {
            order_list_destroy(list);
            return 1;
        }
    }
    printf("orders: %zu, capacity: %zu\n", list->count, list->capacity);
    printf("last id: %d\n", list->ids[list->count - 1]);
    order_list_destroy(list);
    return 0;
}
Output
orders: 5, capacity: 8
last id: 104
  • Verdict: native. C has malloc, calloc, realloc and free in the standard library, and the program decides when each block is freed.
  • order_list_create and order_list_destroy are a pair. The comment on order_list_create states that the caller owns the result.
  • calloc sets the structure to zero, so ids starts as a null pointer. realloc with a null pointer acts as malloc.
  • order_list_add keeps the result of realloc in a second variable, so a failure leaves the old array in the list.
  • order_list_destroy frees the inner array before the structure that points to it.
using System;
using System.Runtime.InteropServices;

const int Count = 4;
IntPtr totals = Marshal.AllocHGlobal(Count * sizeof(int));
try
{
    for (int i = 0; i < Count; i++)
    {
        Marshal.WriteInt32(totals, i * sizeof(int), i * 10);
    }
    Console.WriteLine($"last total: {Marshal.ReadInt32(totals, (Count - 1) * sizeof(int))}");
}
finally
{
    Marshal.FreeHGlobal(totals); // the garbage collector never frees this block
}
Console.WriteLine("freed");
Output
last total: 30
freed
  • Verdict: stdlib. Objects on the managed heap are freed by the garbage collector; Marshal and NativeMemory allocate and free memory outside it.
  • AllocHGlobal does not fill the block with zeros. The program writes each value before it reads it.
  • The finally block frees the memory on every exit, also when an exception leaves the try block.
  • The documentation calls AllocHGlobal a legacy API and recommends NativeMemory.Alloc and NativeMemory.Free. They return a raw pointer and need unsafe code, which this example does not turn on.
RustGitHub
use std::alloc::{alloc, dealloc, handle_alloc_error, Layout};

struct Order {
    id: u32,
    quantity: u32,
}

fn main() {
    let layout = Layout::array::<u32>(4).expect("layout fits in isize");
    unsafe {
        let totals = alloc(layout) as *mut u32;
        if totals.is_null() {
            handle_alloc_error(layout);
        }
        for i in 0..4 {
            totals.add(i).write(i as u32 * 10);
        }
        println!("last total: {}", totals.add(3).read());
        dealloc(totals as *mut u8, layout); // the same layout as alloc
    }

    let order = Box::new(Order { id: 7, quantity: 2 });
    let raw: *mut Order = Box::into_raw(order); // the caller now owns the memory
    unsafe {
        println!("order {} has {} items", (*raw).id, (*raw).quantity);
        drop(Box::from_raw(raw)); // ownership goes back to a Box, which frees it
    }
}
Output
last total: 30
order 7 has 2 items
  • Verdict: stdlib. Safe Rust frees memory through ownership; std::alloc gives unsafe code direct access to the global allocator.
  • dealloc must receive the same Layout that alloc received. A null result from alloc means failure, and handle_alloc_error reports it.
  • Box::into_raw gives up ownership without freeing the memory. Box::from_raw takes it back, and the Box frees the memory when it is dropped.
  • Calling Box::from_raw twice on the same pointer frees the memory twice.
  • Arenas and regions. The program allocates many objects in one region and frees the whole region in one call. Wilson et al. describe Ross's zones and Hanson's obstacks as early forms.18 The Java Arena is a region in this sense.28
  • Pools and size classes. A pool serves objects of one size from a free list for that size. Segregated free lists apply the idea to the whole heap, with size classes that are often powers of two.18 Stroustrup found per-class allocators effective in early C++ programs.22
  • Sized deallocation. free_sized in C and dealloc in Rust take the size of the block, so the allocator need not look it up.124
  • Stack allocation. Memory with a known lifetime can live in a stack frame and needs no free at all. See Stack and heap.
  • Automatic management. Reference counting frees a block when the last reference goes away. Garbage collection frees blocks that the program can no longer reach. Both remove the explicit free, at a cost in time or memory.
  • Use after free. A pointer to a freed block is dangling. Use after free explains this weakness in detail.

Pitfalls

Double free

Two paths free the same block. The second call is undefined behaviour, and it can corrupt the free list of the allocator.1 Here release_order frees the block, and then main frees it again.

This code has a memory error, on purpose, and the sanitizer reports it.

#include <stdio.h>
#include <stdlib.h>

struct order {
    int id;
    int quantity;
};

void release_order(struct order *order) {
    printf("order %d released\n", order->id);
    free(order);
}

int main(void) {
    struct order *order = malloc(sizeof *order);
    if (order == NULL) {
        return 1;
    }
    order->id = 7;
    order->quantity = 2;
    release_order(order);
    free(order); // the block is already free
    return 0;
}

AddressSanitizer reports attempting double-free.9 Without the sanitizer, the second free can seem to work, and the damage shows up later. The fix is one owner for each block. Here release_order takes the address of the pointer, frees the block, and clears the pointer. The second call then frees a null pointer, which does nothing.1

#include <stdio.h>
#include <stdlib.h>

struct order {
    int id;
    int quantity;
};

// Takes ownership: frees the order and clears the caller's pointer.
void release_order(struct order **order) {
    if (*order == NULL) {
        return;
    }
    printf("order %d released\n", (*order)->id);
    free(*order);
    *order = NULL;
}

int main(void) {
    struct order *order = malloc(sizeof *order);
    if (order == NULL) {
        return 1;
    }
    order->id = 7;
    order->quantity = 2;
    release_order(&order);
    release_order(&order);
    printf("order is null: %s\n", order == NULL ? "yes" : "no");
    return 0;
}
Output
order 7 released
order is null: yes

Clearing one pointer does not clear its copies. The rule must hold for the whole program: one owner frees, and the other pointers do not outlive it.

new[] with delete

An array from new[] must go back through delete[].3 The plain delete runs one destructor and passes the wrong pointer or size to the deallocation function.

This code does not compile, on purpose.

#include <print>

struct Line {
    int quantity = 0;
};

int main() {
    Line* lines = new Line[3];
    lines[0].quantity = 5;
    std::println("first quantity: {}", lines[0].quantity);
    delete lines;
}

Clang sees both expressions in one function and warns with -Wmismatched-new-delete. This block turns the warning into an error. When the new[] and the delete are in different functions, the compiler cannot see the mismatch. AddressSanitizer then reports alloc-dealloc-mismatch at run time, but this check is off by default on macOS and Windows.10 The fix is delete[], or a container that owns the array.

#include <print>
#include <vector>

struct Line {
    int quantity = 0;
};

int main() {
    Line* lines = new Line[3];
    lines[0].quantity = 5;
    std::println("first quantity: {}", lines[0].quantity);
    delete[] lines;

    std::vector<Line> owned(3); // frees its array in the destructor
    owned[0].quantity = 5;
    std::println("first quantity: {}", owned[0].quantity);
}
Output
first quantity: 5
first quantity: 5

realloc that loses the old block

When realloc cannot grow a block, it returns a null pointer and leaves the old block where it was.115 The line buffer = realloc(buffer, size) writes that null pointer over the only copy of the old address. The old block is then lost. The program below stands in a failing function for realloc, so that the out-of-memory path runs on every machine.

This code has a memory error, on purpose, and the sanitizer reports it.

#include <stdio.h>
#include <stdlib.h>

// Stands in for realloc when the system has no memory left.
static void *realloc_out_of_memory(void *ptr, size_t size) {
    (void)ptr;
    (void)size;
    return NULL;
}

int main(void) {
    int *buffer = malloc(4 * sizeof *buffer);
    if (buffer == NULL) {
        return 1;
    }
    buffer[0] = 42;
    buffer = realloc_out_of_memory(buffer, 8 * sizeof *buffer);
    if (buffer == NULL) {
        printf("grow failed\n");
        return 0; // the old block is unreachable
    }
    free(buffer);
    return 0;
}

LeakSanitizer reports the block of 16 bytes from malloc. The fix keeps the result in a second variable and replaces the old pointer only on success. On failure, the program still has its data.

#include <stdio.h>
#include <stdlib.h>

// Stands in for realloc when the system has no memory left.
static void *realloc_out_of_memory(void *ptr, size_t size) {
    (void)ptr;
    (void)size;
    return NULL;
}

int main(void) {
    int *buffer = malloc(4 * sizeof *buffer);
    if (buffer == NULL) {
        return 1;
    }
    buffer[0] = 42;
    int *grown = realloc_out_of_memory(buffer, 8 * sizeof *buffer);
    if (grown == NULL) {
        printf("grow failed, first value still %d\n", buffer[0]);
    } else {
        buffer = grown;
    }
    free(buffer);
    return 0;
}
Output
grow failed, first value still 42

The C99 rationale explains that realloc deallocates the old object and allocates another one, even when the address stays the same.2 So any other pointer into the old block is dangling after a successful call.

A leak on an early return

A function with several exits must free its blocks on each exit. An error path is the usual place to forget one. A leak does no visible harm at once; the process only grows. A long-running server can grow until the system stops it. See Memory leak for the general problem and its tools.

This code has a memory error, on purpose, and the sanitizer reports it.

#include <stdio.h>
#include <stdlib.h>

int sum_quantities(const int *quantities, size_t count, int *sum) {
    int *copy = malloc(count * sizeof *copy);
    if (copy == NULL) {
        return -1;
    }
    *sum = 0;
    for (size_t i = 0; i < count; i++) {
        if (quantities[i] < 0) {
            return -1; // copy is not freed
        }
        copy[i] = quantities[i];
        *sum += copy[i];
    }
    free(copy);
    return 0;
}

int main(void) {
    const int quantities[] = {3, -1, 4};
    int sum = 0;
    if (sum_quantities(quantities, 3, &sum) != 0) {
        printf("bad quantity\n");
    }
    return 0;
}

LeakSanitizer finds the block when the process exits. It has almost no cost until then.11 The fix sends every exit through one cleanup label, a common pattern in C.

#include <stdio.h>
#include <stdlib.h>

int sum_quantities(const int *quantities, size_t count, int *sum) {
    int status = -1;
    int *copy = malloc(count * sizeof *copy);
    if (copy == NULL) {
        return -1;
    }
    *sum = 0;
    for (size_t i = 0; i < count; i++) {
        if (quantities[i] < 0) {
            goto done;
        }
        copy[i] = quantities[i];
        *sum += copy[i];
    }
    status = 0;
done:
    free(copy);
    return status;
}

int main(void) {
    const int quantities[] = {3, -1, 4};
    int sum = 0;
    if (sum_quantities(quantities, 3, &sum) != 0) {
        printf("bad quantity\n");
    }
    return 0;
}
Output
bad quantity

In C++ and Rust, a destructor or a drop does this work on each exit, which is the main argument for Resource acquisition is initialization.

The size of the pointer instead of the object

malloc(sizeof order) asks for the size of the pointer, 8 bytes on a 64-bit machine, and not the size of the structure. The writes then go past the end of the block, an Out-of-bounds write.

This code has a memory error, on purpose, and the sanitizer reports it.

#include <stdio.h>
#include <stdlib.h>

struct order {
    int id;
    int quantity;
    double price;
};

int main(void) {
    struct order *order = malloc(sizeof order); // the size of the pointer
    if (order == NULL) {
        return 1;
    }
    order->id = 7;
    order->quantity = 2;
    order->price = 9.5;
    printf("total: %.2f\n", order->quantity * order->price);
    free(order);
    return 0;
}

AddressSanitizer reports a heap-buffer-overflow on the write to price. The glibc manual recommends the form malloc(sizeof *ptr), which takes the size from the object that the pointer points to.12 It stays correct when the type of the pointer changes.

#include <stdio.h>
#include <stdlib.h>

struct order {
    int id;
    int quantity;
    double price;
};

int main(void) {
    struct order *order = malloc(sizeof *order);
    if (order == NULL) {
        return 1;
    }
    order->id = 7;
    order->quantity = 2;
    order->price = 9.5;
    printf("total: %.2f\n", order->quantity * order->price);
    free(order);
    return 0;
}
Output
total: 19.00

Cost

  • Header and rounding. Each block carries a header. Wilson et al. give an example: a one-word header on objects of about 10 words costs about 10% of the memory.18 The glibc wiki lists typical 64-bit values: blocks are aligned to 16 bytes, and the smallest chunk is 32 bytes.17
  • Time per call. A call is usually a few list operations, but it is not constant. A search, a split or a coalesce can run, and a request can reach the operating system. Stroustrup reports early C++ programs that spent 50% or more of their time in malloc.22
  • Large blocks. glibc serves a request above the mmap threshold with its own mapping. The threshold changes with the allocation pattern of the program. The glibc wiki lists a default of 128 KiB and a maximum of 32 MiB on 64-bit systems.1617
  • Memory that stays in the process. free puts most blocks back on a free list, not back to the operating system.14 Fragmentation can keep the process large after the program frees most of its data.
  • Threads. glibc gives threads separate arenas to reduce lock contention, up to eight times as many arenas as there are CPUs.17
  • Checking. AddressSanitizer finds double frees and invalid frees with a typical slowdown of about two times.9 Release builds usually run without it, so tests must find these bugs.

History

  • 1979. The Seventh Edition Unix manual, edited by McIlroy and Kernighan, documented malloc, free, realloc and calloc. The allocator used first fit and coalesced free neighbours during its search.1921 Its BUGS section warned that when realloc returned 0, the old block could be destroyed. The Sixth Edition library before it had alloc and free, which returned -1 when no memory was left.20
  • 1979 to 1983. Stroustrup built C with Classes and added the new and delete operators. new allocates and runs a constructor, an idea from Simula. delete was added because he did not want the language to depend on a garbage collector.22
  • 1989. The ANSI committee X3J11 finished the C standard X3.159-1989, which ISO accepted as ISO/IEC 9899-1990.21 The rationale records that the committee rejected zero-length objects for these functions.2
  • 1993. Ritchie wrote that C provides allocated storage only through a library routine, and the programmer carries the burden. In his words, "C is hostile to automatic garbage collection."21
  • 1995. Wilson, Johnstone, Neely and Boles published a survey of allocators that set the terms for fragmentation, splitting, coalescing and segregated free lists.18
  • 1999. C99 defined realloc as the deallocation of the old object and the allocation of another one. C89 had treated the result as the same object.2
  • 2011. C11 added aligned_alloc.1
  • 2024. C23, ISO/IEC 9899:2024, added free_sized and free_aligned_sized, and made a realloc to size zero undefined behaviour.1 JEP 454 completed the Java Foreign Function and Memory API in JDK 22, after previews in JDK 19, 20 and 21. Its Arena manages memory outside the heap.29

References

  1. ISO/IEC 9899:2024 (en), N3220 working draft (C23), 6.2.4 Storage durations of objects; 7.24.3 Memory management functions, 7.24.3.1 to 7.24.3.7; Annex M.2 and M.4
  2. Rationale for International Standard, Programming Languages, C, Revision 5.10, 7.20.3 Memory management functions; 7.20.3.2 The free function; 7.20.3.4 The realloc function
  3. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [expr.delete] 7.6.2.9, paragraph 2 and note 1
  4. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [new.delete.single] 17.6.3.2, the throwing and the nothrow forms of operator new
  5. C++ Core Guidelines, I.11: Never transfer ownership by a raw pointer (T*) or reference (T&)
  6. C++ Core Guidelines, R.3: A raw pointer (a T*) is non-owning
  7. C++ Core Guidelines, R.10: Avoid malloc() and free()
  8. C++ Core Guidelines, R.11: Avoid calling new and delete explicitly
  9. Clang documentation, AddressSanitizer, Introduction; Memory leak detection
  10. google/sanitizers wiki, AddressSanitizerFlags, the run-time flag alloc_dealloc_mismatch
  11. Clang documentation, LeakSanitizer, Introduction
  12. The GNU C Library Reference Manual, 3.2.3.1 Basic Memory Allocation
  13. The GNU C Library Reference Manual, 3.2.3.2 Examples of malloc
  14. The GNU C Library Reference Manual, 3.2.3.4 Freeing Memory Allocated with malloc
  15. The GNU C Library Reference Manual, 3.2.3.5 Changing the Size of a Block
  16. The GNU C Library Reference Manual, 3.2.2 The GNU Allocator
  17. glibc wiki, Overview of Malloc, What is a Chunk?; Arenas and Heaps; Thread Local Cache (tcache); Free Algorithm; Platform-specific Thresholds and Constants
  18. Paul R. Wilson, Mark S. Johnstone, Michael Neely and David Boles, Dynamic Storage Allocation, A Survey and Critical Review, International Workshop on Memory Management (IWMM), LNCS 986, 1995, 1.3 Splitting and coalescing; 2.1 Internal and external fragmentation; 3.2 Header fields and boundary tags; 3.6 Segregated free lists; the section on obstacks and zones
  19. Unix Programmer's Manual, Seventh Edition, malloc(3), DESCRIPTION, DIAGNOSTICS and BUGS
  20. Unix Programmer's Manual, Sixth Edition, alloc(3), DESCRIPTION and DIAGNOSTICS
  21. Dennis M. Ritchie, The Development of the C Language, HOPL-II, 1993, the sections Standardization and Critique
  22. Bjarne Stroustrup, A History of C++, 1979-1991, HOPL-II, 1993, 2 C with Classes, 1979-1983; 3.3.6 Memory Management
  23. The Rust Standard Library, function std::alloc::alloc, function description and example
  24. The Rust Standard Library, trait std::alloc::GlobalAlloc, alloc and dealloc, Safety
  25. The Rust Standard Library, struct std::boxed::Box, into_raw and from_raw
  26. .NET API, Marshal.AllocHGlobal Method, Remarks
  27. .NET API, NativeMemory Class, Methods
  28. Java SE 25 API, java.lang.foreign.Arena, the table of arena kinds; ofConfined(); close()
  29. JEP 454: Foreign Function & Memory API, Summary and History
  30. Go FAQ, Why do garbage collection? Won't it be too expensive?
  31. Go command documentation, cgo, C.CString, C.free and C.malloc
  32. Python/C API Reference Manual, Memory Management, Python 3.14, Overview; PyMem_Malloc and PyMem_Free
  33. Kotlin documentation, Interoperability with C, Memory allocation, nativeHeap and memScoped

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/1T4M29/text.yaml