Skip to content
All articles

C Programming

malloc and free in C: dynamic memory and how to find memory leaks

In C, memory is your responsibility: every byte you take, you must give back. Here's how to use malloc and free correctly, the most common mistakes, and how to catch them with Valgrind and AddressSanitizer.

Fahrettin Baştürk4 min read

What I love about C, and what people fear most, is that memory is entirely your responsibility. There's no garbage collector, no runtime thinking for you. Every byte you take, you must give back. It looks like a burden, but it's also the best way to understand how the machine really works.

The stack and the heap

Variables declared inside a function live on the stack and disappear when the function returns. But for data whose size is only known at runtime, or that must outlive the function, you need to request memory from the heap.

#include <stdlib.h>
#include <string.h>

int *numbers = malloc(n * sizeof *numbers);
if (numbers == NULL) {
    /* out of memory; always check */
    return -1;
}
/* ... use ... */
free(numbers);
numbers = NULL;   /* so it isn't reused by accident */
  • malloc(size): allocates that many bytes; contents are indeterminate.
  • calloc(count, size): allocates and zeroes.
  • realloc(ptr, new_size): grows or shrinks the block, moving it if needed.
  • free(ptr): gives the block back.

Writing sizeof *numbers is a small but good habit: if the pointer's type changes, the size stays correct automatically.

The realloc trap

p = realloc(p, new_size);   /* wrong */

If realloc fails it returns NULL, but the old block is not freed. Assigning the result straight to p loses the old block's address and leaks memory. The right way is to use a temporary:

int *tmp = realloc(p, new_size * sizeof *p);
if (tmp == NULL) { free(p); return -1; }
p = tmp;

The four most common mistakes

  1. Memory leak: memory that was malloced is never freed. In short programs you won't notice, but in a long-running server, memory slowly fills up.
  2. Double free: freeing the same block twice. It corrupts the heap and can be exploited by attackers.
  3. Use-after-free: continuing to use a freed block. It sometimes seems to work, which is exactly why it's one of the most dangerous bugs.
  4. Overflow: writing past the allocated block. For example, allocating strlen(s) bytes for a string and leaving no room for the trailing '\0'.

Finding bugs: Valgrind and AddressSanitizer

None of these are easy to spot by eye. Fortunately there are excellent tools.

Valgrind (Linux) runs the program on a virtual machine and watches every memory access:

gcc -g program.c -o program
valgrind --leak-check=full ./program

In the output, "definitely lost" lines show leaks, and "Invalid read/write" lines show overflows and use-after-free, along with the line where the memory was allocated.

AddressSanitizer is built into the compiler and much faster:

gcc -g -fsanitize=address program.c -o program
./program

The program stops at the moment of the bug and gives you a full stack trace. I now compile every C project with ASan on during development; running unit tests this way catches most bugs before they ever show up. I also wrote about using the same tool together with fuzzing.

Think in terms of ownership

Beyond the technical rules, the most useful habit is asking, for every pointer: "who owns this memory, and who will free it?" If a function allocates memory and returns it, document that; and where possible, keep freeing in the same module that allocates. Smart pointers in C++ are this idea of ownership built into the language.

Memory management in C is hard, but that difficulty teaches you something: nothing is free. Every allocated byte is a promise, and keeping that promise is the programmer's job.

Fahrettin Baştürk

Software Engineer & Consultant

Share
  • C
  • Memory Management
  • Valgrind
  • Learning C

Working on a similar system or problem?Tell me about your project