C allows us to define variables as follows:
// A variable declared inside a function will usually be stored on the stack.
int a = 42;
// A variable declared with `static` or at file scope will usually be stored in `.data`
// or `.rodata`.
static int b = 2026;
The storage for these variables is managed by the language itself. However, sometimes we need to manage memory manually. In such cases, we can obtain dynamically allocated memory using functions such as malloc(), calloc() and realloc().
// Dynamically allocated memory will usually come from the heap.
int *c = malloc(sizeof *c);
*c = 42;
When the memory is no longer needed, we deallocate it using free().
free(c);
This gives us the flexibility to allocate and deallocate memory as needed, allowing us to implement all kinds of complex data structures and, consequently, many things that would be difficult or impossible with only statically allocated memory.
However, this approach also introduces a problem.
Consider the following scenario:
int *a = malloc(sizeof *a);
int *b = a;
Who is responsible for deallocating the memory?
Clearly, leaving the allocation undeallocated is not a solution, as this would result in a memory leak. Nor is deallocating it through both pointers, as this would cause undefined behaviour under ISO/IEC 9899 and is commonly referred to as a double free.
We should deallocate the memory through just one of these pointers. But how do we determine which one? This introduces us to an important concept in memory management, and resource management in general: ownership.
Ownership, borrowing and transfer
Ownership is a contract that specifies which part of a programme is responsible for managing a resource and deallocating it when it is no longer needed. We say that a pointer variable owns the memory when it is designated as responsible for releasing that allocation using free().
To explain how ownership helps us manage resources properly, let’s implement a linked list. First, define the following structure:
typedef struct N
{
int data;
struct N *previous;
struct N *next;
} Node;
We use previous == NULL to indicate a guard node (whose data member is meaningless), and next == NULL to indicate the last item in the linked list.
Suppose we have a Node variable defined at file scope and use it as our guard node:
Node l = {0, NULL, NULL};
We need some functions to manipulate this linked list.
Let’s define the following functions:
Node *getNode(Node *guard, int index)
{
if (index < 0)
return NULL; // The index is negative.
else if (index > 0 && guard->next == NULL)
return NULL; // The index is out of range.
else if (index == 0)
return guard->next;
else return getNode(guard->next, index - 1);
}
void setData(Node *x, int data)
{
x->data = data;
}
int getData(Node *x)
{
return x->data;
}
Here are some statements from our main() function:
/* ... */
Node *a = malloc(sizeof *a);
a->previous = NULL;
a->next = NULL;
setData(a, 42);
printf("%d\n", getData(a));
/* ... */
Who is responsible for deallocating the memory pointed to by a after setData() and getData() have been called? Obviously, it is still a. setData() and getData() only read or modify the memory passed to them through their parameters; they neither allocate nor deallocate memory. They do not pass the pointers to other functions or global variables that will also manage the memory. We therefore say that these functions borrow the memory rather than take ownership of it.
Borrowing means that a function receives access to a resource without taking responsibility for its lifetime. The function may read or modify the resource, depending on the interface contract, but must not independently release it.
The same applies to getNode(): it traverses the linked list and retrieves a node by index. It neither allocates nor deallocates memory, nor does it transfer ownership of anything.
However, this is not always the case. Consider the following functions:
Node *createNode(int data)
{
Node *ans = malloc(sizeof *ans);
if (! ans)
exit(EXIT_FAILURE);
ans->data = data;
ans->previous = NULL;
ans->next = NULL;
return ans;
}
int insertNode(Node *guard, Node *n, int index)
{
if (index < 0)
return 1; // The index is negative.
else if (index > 0 && guard->next == NULL)
return 2; // The index is out of range.
else if (index == 0)
{
if (guard->next)
{
n->next = guard->next;
guard->next->previous = n;
}
n->previous = guard;
guard->next = n;
return 0;
}
else return insertNode(guard->next, n, index - 1);
}
We can now pass a to insertNode() to insert the node we have allocated into the linked list:
/* ... */
insertNode(&l, a, 0);
/* ... */
What happens now?
Obviously, we should no longer call free() on a after successfully calling insertNode(), as doing so would break the linked list. Instead, the node should be deallocated when we destroy the linked list:
void destroyExceptGuard(Node *guard)
{
if (guard == NULL)
return;
Node *current = guard->next;
guard->next = NULL;
while (current != NULL)
{
Node *next = current->next;
free(current);
current = next;
}
}
When insertNode() successfully inserts a node, ownership of that node is transferred from the caller to the linked list. The function carries out this transfer, but the linked list becomes responsible for the node after insertion.
The function createNode() does the opposite: it allocates memory and returns a pointer to it. After the function returns, it is no longer responsible for deallocating the memory. Instead, responsibility passes to the caller, which receives the returned pointer. We say that the function transfers ownership to the caller.
Lifetimes — How long should a resource live?
Having ownership means that the owner is responsible not only for deallocating the memory, but also for deciding when to do so. In other words, the owner determines the resource’s lifetime.
More generally, ownership is a programming contract that establishes which part of a programme is responsible for managing a resource’s lifetime and, in particular, releasing it when it is no longer needed. A pointer may refer to a resource without owning it, and multiple pointers may refer to the same resource.
In C, the lifetime of an object in allocated storage is managed using free() and other functions that can modify the allocation. The object exists from the time it is allocated until one of these functions is called on the allocation.
Take another look at our linked-list node:
typedef struct N
{
int data;
struct N *previous;
struct N *next;
} Node;
A complete, well-formed linked list should contain a guard node and some item nodes whose pointers are correctly linked to one another. If a node is deallocated without first updating the relevant pointers, the neighbouring nodes may retain pointer values that refer to an object whose lifetime has ended. These pointers must not be used. Consequently, traversing the linked list through these relationships can cause undefined behaviour. Furthermore, the nodes following the destroyed node may become unreachable when traversing the list from the guard node.
When discussing a pointer’s lifetime, we are usually referring to the lifetime of the object it points to, rather than the lifetime of the pointer variable itself. The pointer variable also has its own lifetime, but this is separate and does not affect the lifetime of its referent.
Lifetime issues are not limited to dynamically allocated memory, whose lifetime we manage ourselves. For example, suppose we replace createNode() with the following implementation:
Node *createNode(int data)
{
Node ans;
ans.data = data;
ans.previous = NULL;
ans.next = NULL;
return &ans;
}
This implementation is invalid because the lifetime of ans lasts only while the function is executing. It ends when the function returns, at which point the returned pointer no longer refers to a live object.
Adding static to Node ans would not solve the problem. It would give ans a lifetime that extends throughout the entire execution of the programme, but every function call would refer to the same object rather than creating a new one.
Ownership and lifetimes in different programming languages
In C, ownership is not enforced by the language itself. Instead, it is a contract that programmers establish and follow to avoid crashes and unexpected behaviour. Object lifetimes, by contrast, are defined by the language itself.
In some other programming languages, ownership is enforced by the language itself. Rust is a notable example: it has an ownership system enforced by its compiler. Every value has an owner, and ownership can be transferred between variables through move semantics. References (&T and &mut T) allow other parts of the programme to borrow values without taking ownership. Rust’s lifetime rules ensure that borrowed references cannot outlive the values they refer to. For example, String is an owning type that manages a dynamically allocated buffer containing its string data, whereas &str is a borrowed string slice. Rust also provides types such as Rc<T> and Arc<T> for shared ownership.
C++ uses RAII and combines automatic resource management with facilities for manual management. We can manage memory manually using new and delete, or use smart pointers such as std::unique_ptr<T> and std::shared_ptr<T>, which are provided by the C++ standard library. These objects encapsulate ownership information for dynamically allocated memory, allowing the language to manage resources automatically. We can also implement our own smart pointers. std::unique_ptr<T> enforces exclusive ownership, behaving similarly to exclusive-ownership contracts in C, while managing the resource automatically. std::shared_ptr<T> uses a counter to track how many variables share ownership of a resource. It deallocates the resource automatically when no variable retains shared ownership.
Languages such as Python generally use automatic memory management rather than requiring programmers to explicitly allocate and deallocate memory. CPython, for example, uses reference counting together with a cyclic garbage collector.