Dynamically Allocated Structures: Building and Owning Nodes
A dynamically allocated structure is a structure object whose storage is obtained at runtime and remains allocated until it is explicitly released. In C, these objects let you build collections whose size changes during execution. A local pointer can refer to such an object, but the pointer going out of scope does not release the object. You must track both the links between structures and responsibility for their storage.
Allocate and initialize a complete object
A node combines a stored value with a pointer to another node. This declaration describes the node type; it does not allocate any nodes:
typedef struct Node {
int value;
struct Node *next;
} Node;The pointer member can refer to another object of the same structure type. A structure cannot contain a complete instance of itself directly, because that would require an unbounded object size.
With the standard allocation functions declared, the following code can run inside a function:
Node *p = malloc(sizeof *p);
if (p != NULL) {
p->value = 7;
p->next = NULL;
}Here, malloc requests storage for one complete node. In this expression, sizeof *p determines the size from the type without evaluating *p. Successful allocation supplies storage, but does not initialize the members. Check for allocation failure before accessing any member.
For separately allocated nodes of one type, the requested storage is
where N counts nodes that have been allocated and not yet freed. This counts object storage, excluding allocator bookkeeping. The structure size includes any padding required by the implementation.
Link nodes without losing the chain
A singly linked list can use head to identify its first node and NULL to mark its end.
To prepend an initialized node p, preserve access to the existing chain before replacing its entry pointer:
p->next = head;
head = p;If you assign head = p first and then execute p->next = head, the new node points to itself. You have also lost the original entry pointer unless another pointer preserves it.
Copying a pointer does not create another node. Copying a structure copies its member values, including any stored addresses; it does not duplicate the objects reached through those addresses.
Operation | Creates another allocated node? | Effect |
|---|---|---|
Successful malloc(sizeof *p) | Yes | Obtains storage requiring initialization |
Node *q = p | No | Gives another pointer access to the same node |
Node copy = *p | No | Creates a local structure with copied member values |
free(p) | No | Releases that node, without following its links |
Own and release the nodes
Ownership identifies which part of the program is responsible for releasing an allocation. Several pointers may reach the same node, but cleanup must release each allocation exactly once. Releasing one node neither frees its successors nor makes other pointers to it safe to use.
For an acyclic list whose nodes were allocated separately and are owned by that list, cleanup can advance as follows:
while (head != NULL) {
Node *next = head->next;
free(head);
head = next;
}Read the successor before freeing the current node. Once the node is freed, accessing its next member is invalid. The saved pointer lets the loop continue without reading released storage.
What to remember
- Allocate the complete structure and initialize its members after checking success.
- Preserve the existing chain before changing its entry pointer.
- Pointer and structure copies do not duplicate linked allocations.
- Save needed links before freeing a node, and release each owned allocation once.
Example: Maintain a sensor-reading list
A C program stores pending sensor readings in separately allocated nodes:
typedef struct Node {
int value;
struct Node *next;
} Node;On the stated platform, sizeof(Node) is 16 bytes, including padding. Standard allocation functions are declared. The initial list contains readings 18 and 27 in that order. Treat head as the owning pointer: it identifies the chain this routine is responsible for eventually freeing. No other part of the program retains pointers to these nodes.
Assume the new allocation succeeds. Count only requested node storage, excluding allocator bookkeeping and local pointer variables. Perform the following parts consecutively.
a) Prepend reading 41. Show the allocation and linking code, state the resulting order, and calculate the requested node storage.
First account for the existing allocations. The initial requested storage is ________, because two nodes are allocated. One additional node requires ________.
Allocate the complete node. The failure check is included so that an unsuccessful allocation would leave the original list unchanged; here, the stated assumption means execution continues past it.
Node *p = malloc(sizeof *p);
if (p == NULL) {
return;
}
p->value = 41;
p->next = head;
head = p;The assignment to p->next preserves the original first node before head is replaced. The resulting order is 41 -> 18 -> 27 -> NULL.
There are now three separately allocated nodes:
The list order is 41, 18, 27, and the requested node storage is 48 bytes.
b) Remove the node containing 18. Show safe code and calculate the requested storage remaining after its release.
After part a, the node containing 18 is immediately after head. Identify it before changing the incoming link:
Node *victim = head->next;
Node *successor = victim->next;
head->next = successor;
free(victim);
victim = NULL;
successor = NULL;The saved successor contains ________. Reading that pointer before the release lets you repair the chain without accessing the removed node afterward. Clearing the temporary variables changes pointer values; it does not release the successor.
After relinking and freeing the removed allocation, ________ remain. Their requested storage is
The list order is 41, 27, and the requested node storage remaining is 32 bytes.
c) Release the remaining list. Show safe traversal code, determine how many bytes this cleanup releases, and state the final value of head.
Both remaining nodes were allocated separately, so each needs its own release. Save the next pointer while the current node is still live:
while (head != NULL) {
Node *next = head->next;
free(head);
head = next;
}
p = NULL;The loop performs ________. During the first iteration, it saves the address of the node containing 27 and frees the node containing 41. During the second, it saves NULL and frees the final node. Setting p to NULL afterward clears the leftover alias from part a without dereferencing it.
This cleanup releases
Across all three parts, three nodes were allocated and three were freed: one in part b and two here. The cleanup releases 32 bytes, leaves 0 bytes of node storage allocated, and ends with head == NULL.
A program builds linked records with malloc and free. Match each term about dynamically allocated structures to the situation it describes.
A second pointer variable holding the same address as another, so both name one node
Member-by-member struct assignment, leaving pointer members in both structs aimed at the same heap block
A pointer that still holds the address of a node after that node's storage has been released
Releasing the same allocated address a second time, which is undefined behaviour
The pointer whose holder is responsible for passing the block to free exactly once
Duplicating a struct and also allocating fresh storage for every block its pointer members own
An allocated block that no remaining pointer can reach, so the program can never release it
Shallow copy
Alias
Double free
Dangling pointer
Memory leak
Deep copy
Owning pointer
In a C program, a and tail point to two separate, successfully allocated Node objects. Each node has an integer value and a pointer member next. Initially, a->value is 86, a->next is tail, and tail->next is NULL.
The program executes:
Node *b = a;
Node snapshot = *a;Which statements are true? Select every true statement. Evaluate each proposed change independently from this state.