Freeing dynamically allocated structs
What you'll learn: How to properly release memory for a structure created with malloc to prevent memory leaks in your programs.
The "Russian Doll" Problem
When you use malloc to create a struct, you are asking the computer to carve out a specific block of memory on the "heap." Think of this struct like a storage box. If that box contains only simple variables (like integers or floats), deleting the box is easy: you just throw the whole thing away.
However, if your struct contains pointers to other blocks of memory (like a string created with strdup or another dynamic array), the struct becomes like a Russian nesting doll. If you simply free the outer box, the smaller items inside are trapped in memory forever. This is the most common way C programmers accidentally create memory leaks.
The Two-Step Teardown
To safely free a dynamically allocated struct, you must follow a simple rule: Work from the inside out. You must free every pointer member inside the struct before you free the pointer to the struct itself. Once you call free() on the main struct pointer, you lose your "handle" to those internal addresses, and that memory becomes unreachable.
Here is how you handle a struct that contains dynamic data:
#include <stdlib.h>
#include <string.h>
struct User {
char *name; // Dynamically allocated string
int id;
};
int main() {
// 1. Allocate the struct itself
struct User *u = malloc(sizeof(struct User));
// 2. Allocate memory for the internal member
u->name = malloc(50 * sizeof(char));
strcpy(u->name, "Alice");
u->id = 1;
// --- CLEANUP PHASE ---
// Step A: Free the inner members first
free(u->name);
// Step B: Free the struct itself last
free(u);
// Step C: Prevent accidental reuse (optional but smart)
u = NULL;
return 0;
}
Why the order matters
Imagine you are moving out of an apartment. If you give the keys back to the landlord (freeing the struct) while your furniture is still inside (the internal pointers), you can no longer get back in to get your stuff. The furniture stays there, taking up space, but nobody can use it. Always empty the rooms before you hand over the keys.
Key takeaway
Always free() dynamic members inside a struct before freeing the pointer to the struct itself to avoid memory leaks.