C Reference ยท stdlib.h
Memory ownership patterns in C
Learn the standard C ownership patterns: caller-supplied buffers, returned allocations, borrowed pointers, transfer of ownership and create/destroy pairs.
C has no garbage collector and no destructors. Every block you get from malloc() must be released exactly once with free(), and the language does not record who is responsible. Ownership is therefore a convention: at any moment exactly one piece of code owns each allocation and must free it, and every other pointer to it is merely borrowed.
Most memory bugs (leaks, double frees, use after free) come from unclear ownership. This page lists the patterns used in well-designed C libraries, so that every function you write can state in its comment who owns what.
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
The patterns
Caller supplies the buffer. The function receives char *out, size_t size and fills it. No allocation, no ownership question, no cleanup. This is the safest design; snprintf and fgets work this way. Always pass the size.
Callee allocates, caller frees. The function returns a malloc'd pointer (or NULL). Document this loudly, because the caller cannot tell from the type. Many libraries use a naming convention (make_*, new_*, *_create) and provide the matching release function. Return NULL on failure rather than a half-built object.
Borrowed pointers. A const char * parameter normally means "read this, do not keep it, do not free it". If a function needs the data after it returns, it must copy (strdup). A struct that stores a borrowed pointer is only valid while the original lives, which is a common source of use-after-free.
Create/destroy pairs. Opaque structures come with thing_create() and thing_destroy(). The destroy function frees nested allocations first, then the structure, and accepts NULL like free does.
Transfer of ownership. Passing a pointer into a function that stores it (such as list_add_owned(list, item)) moves the duty to free to the new owner. Set the old pointer to NULL so you cannot free it twice. Say in the function's comment whether it copies or takes over.
Single exit cleanup. In functions with several allocations, use a goto cleanup; label at the end that frees everything allocated so far (initialize all pointers to NULL first). It avoids duplicated cleanup code and leaks on error paths.
Usage notes
- Free in the same layer that allocates. On Windows, memory allocated in a DLL should be freed by the same DLL, because each module may link its own C runtime. Providing
lib_free()solves this. - Set freed pointers to
NULLwhere it is cheap to do so; it turns a double free into a harmless no-op and a later use into a visible crash. - Lifetime of returned
staticbuffers: functions such asstrtokorgetenvreturn pointers into internal storage; the next call can overwrite it. Copy if you keep it. - Check every allocation.
malloccan returnNULL; propagate the failure upward. - Tools: compile with
-fsanitize=address,undefinedand runvalgrindto find leaks and invalid frees (see sanitizers and Valgrind). - Arrays of owned strings: free each element, then the array. Freeing only the array leaks every string.
Related
malloc,free, Memory errors,strdup, Opaque types- Lessons: Dynamic memory, Memory errors