Stupid Smart Pointers in C
Published on: 2025-06-14 20:29:04
Managing memory in C is difficult and error prone. C++ solves this with smart pointers like std::unique_ptr and std::shared_ptr . This article demonstrates a proof-of-concept (aka stupid) smart pointer in C with very little code. Along the way we'll look at the layout of the 32-bit x86 call stack and write assembly in a C program.
In C, heap memory is allocated with a call to malloc and deallocated with a call to free . It is the programmer's responsibility to free allocated memory when no longer in use. Otherwise, memory leaks grow the program's memory usage, exhausting valuable system resources.
Sometimes knowing where to call free is clear.
char *data = (char *) malloc (100); // do something with data, don't need it anymore free (data);
But even simple cases may be difficult to properly free. For example, suppose a function f allocates resources in order and frees them before returning.
void f () { char *resource_1 = get_resource (); if (resource_1 == NULL) return; char *resour
... Read full article.