Skip to content
Tutorials Center
My learning

Topics

Lesson 53 of 135 ยท Memory Management

Dynamic Memory: malloc, calloc, realloc and free

Learn dynamic memory in C - allocate on the heap with malloc and calloc, grow blocks safely with realloc, check for NULL, use the sizeof *p idiom and free memory.

Every variable you've written so far had a size fixed when you wrote the program and a lifetime decided by where you declared it. A local array inside a function exists only while that function runs, and its length must be known (or at least computed) when the block starts. Real programs constantly need more flexibility: a list of names whose length depends on a file, a buffer that grows as the user types, or a data structure that must outlive the function that built it.

C gives you that flexibility with dynamic memory: memory you request from the heap while the program runs, and give back when you're done. Four functions from <stdlib.h> do the whole job: malloc, calloc, realloc and free. They are small and simple, but using them correctly is one of the most important skills in C. Nothing frees memory for you, and nothing stops you from using memory after you've freed it. This lesson shows the correct patterns; the next one, Memory Errors, shows what goes wrong when you skip them.

Stack versus heap

Local variables normally live on the stack. The stack is fast and automatic: space appears when a function is called and disappears when it returns. That automatic cleanup is exactly its limitation. You can't return a pointer to a local array, because the array is gone the moment the function returns (you saw this trap in Pointers and Functions). The stack is also small, often 1 to 8 MB, so a local array of a hundred million ints crashes the program.

The heap is a large pool of memory managed by the C library. You ask for a block of a given number of bytes, you get a pointer to it, and the block stays valid until you explicitly release it. Where the stack and heap sit in a running program is the topic of Memory Layout of a C Program.

Stack (automatic) Heap (dynamic)
How you get it Declare a local variable Call malloc, calloc or realloc
Size decided When the block starts Any time, at run time
Lifetime Until the block ends Until you call free
Typical limit A few megabytes Most of the machine's memory
Who cleans up The compiler You

malloc: ask for bytes

malloc(size) allocates size bytes and returns a void * pointing at the first one. If the request can't be satisfied, it returns NULL. The memory is not initialized: it holds whatever bytes happened to be there, so you must write to it before you read it.

C Your first malloc

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Three habits in that program are worth adopting from day one:

  1. Check for NULL. Allocation can fail, especially for large requests or on small embedded devices. Dereferencing a NULL result is undefined behavior; checking costs one if.
  2. Use sizeof *scores, not sizeof(int). The expression sizeof *scores means "the size of whatever scores points to". If you later change int *scores to long *scores, the allocation stays correct automatically. With sizeof(int) you'd have a silent bug. sizeof doesn't evaluate its operand, so *scores is never actually read.
  3. Don't cast the result. In C, a void * converts to any object pointer type implicitly, so int *p = malloc(...) is complete. The cast (int *)malloc(...) is required in C++ but in C it only adds noise. You'll still see it in older code.

Once you have the pointer, you index it like an array, because pointers and arrays share the same subscript syntax: scores[i] is *(scores + i).

Note: malloc(0) is allowed, but the result is implementation-defined: it may return NULL or a unique pointer you must not dereference. Avoid relying on either behavior. If a size can be zero, handle that case yourself.

free: give memory back

free(p) returns a block to the heap. Every pointer you got from malloc, calloc or realloc must be passed to free exactly once. After that, the pointer still holds the old address, but the memory no longer belongs to you. It's now a dangling pointer, and reading or writing through it is undefined behavior.

That's why the example sets scores = NULL right after freeing. It doesn't fix every problem (other copies of the pointer still dangle), but a NULL pointer fails loudly instead of silently corrupting memory, and free(NULL) is guaranteed to do nothing, so a second accidental free becomes harmless.

Some rules that are easy to forget:

  • Pass free the exact pointer the allocator returned, not a pointer into the middle of the block.
  • Never free memory you didn't allocate: string literals, local arrays and global variables are not heap memory.
  • When main returns, the operating system reclaims everything. That doesn't make leaks acceptable: a long-running server or a function called a million times will run out of memory long before it exits.

calloc: zeroed arrays

calloc(count, size) allocates an array of count elements of size bytes each, and sets every byte to zero. For integers, that means every element is 0; on all mainstream platforms, zero bytes are also 0.0 for floating point and a null pointer for pointers.

calloc has a second advantage: it checks the multiplication. With malloc(count * size), a huge count can overflow the size_t result and quietly allocate a tiny block. A correct calloc returns NULL instead.

C calloc gives you zeros

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output shows 0.00 for every day you didn't set, followed by total: 15.75 mm. With malloc, those days would hold garbage. Use calloc when "everything starts at zero" is what you want; use malloc when you're about to overwrite every element anyway and zeroing would be wasted work.

realloc: grow or shrink a block

realloc(p, new_size) changes the size of a block you already own. It keeps the old contents (up to the smaller of the two sizes) and returns a pointer to the resized block. That pointer may be the same address, if there was room to grow in place, or a different one, if the library had to allocate a new block, copy the data and free the old one. Any extra bytes at the end are uninitialized.

There's one trap that catches almost everyone: if realloc fails, it returns NULL and leaves the original block untouched. So this common line is a bug:

C
numbers = realloc(numbers, new_count * sizeof *numbers);   /* leaks on failure */

If realloc fails, numbers becomes NULL, and the only pointer to the old block is gone. You can't use it or free it. The safe pattern assigns to a temporary first:

C Growing an array safely with realloc

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The program grows from 2 to 4, 8 and then 16 slots, and prints the first ten squares: 1 4 9 16 25 36 49 64 81 100. Doubling the capacity keeps the number of realloc calls small, so adding an element is cheap on average. You'll turn this idea into a reusable data structure in Building a Dynamic Array.

Two special cases complete the picture. realloc(NULL, size) behaves exactly like malloc(size), which lets you start with an empty NULL pointer. Calling realloc with a size of zero is a different story: its behavior was implementation-defined, and C23 made it undefined. Call free instead.

Warning: after a successful realloc, every other pointer into the old block may be dangling, because the data might have moved. If you kept a pointer to values[3] before growing, re-compute it from the new values afterwards. Storing indexes instead of pointers avoids the problem.

Returning heap memory from a function

Because heap memory outlives the function that allocated it, a function can build something and hand it to its caller. The deal must be clear, though: who frees it? The usual C convention is to document it in the function's comment, and often to name a matching cleanup function.

C A function that returns a new string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The size calculation counts the space between the names and the terminating '\0', which is the classic off-by-one spot in string code (see Safe String Handling). sizeof isn't needed here because sizeof(char) is always exactly 1.

C23 also standardized strdup and strndup, which allocate a copy of a string with malloc. They existed on POSIX systems for decades; now they're part of standard C. The copy must still be freed by you.

Allocating a two-dimensional table

A common question is how to allocate a grid whose dimensions arrive at run time. The simplest robust answer is one block of rows * cols elements, indexed as grid[r * cols + c]. It needs a single malloc and a single free, keeps the data contiguous (which is fast to scan), and can't half-fail.

C A run-time sized grid in one block

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The alternative, an array of row pointers each with its own malloc, lets you write grid[r][c] and give rows different lengths, but needs rows + 1 allocations and a loop to free them. You'll see that shape with arrays of strings in Pointers to Pointers. With C99 variably modified types you can also write int (*grid)[cols] = malloc(rows * sizeof *grid); and index grid[r][c] with a single block, as long as your compiler supports VLAs (they became optional in C11; see Multidimensional Arrays).

A checklist for every allocation

Before moving on, here's the routine that keeps dynamic memory boring, which is exactly what you want:

  • Compute the size with count * sizeof *p, or let calloc(count, sizeof *p) do the multiplication safely.
  • Check the result against NULL and handle the failure (often: clean up and return an error code).
  • Initialize what you read: malloc and the grown part of a realloc contain garbage.
  • Grow with realloc through a temporary pointer.
  • Decide who owns the block and write it down. Every owner frees exactly once.
  • After free, set the pointer to NULL if it stays in scope.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does int *p = malloc(4 * sizeof *p); contain right after a successful call?

    malloc does not initialize memory. Use calloc if you need zeros, or write every element before reading it.
  2. 2. Why is data = realloc(data, n * sizeof *data); considered a bug?

    On failure the old block is still valid, but the only pointer to it was replaced with NULL. Assign to a temporary, check it, then update data.
  3. 3. Which call is guaranteed to do nothing?

    The standard says free(NULL) has no effect. The other three are undefined behavior.
  4. 4. You change int *items to long long *items. Which allocation stays correct without edits?

    sizeof *items always follows the pointed-to type, so the allocation adapts when the type changes.
  5. 5. What is one advantage of calloc(count, size) over malloc(count * size)?

    calloc checks the multiplication and returns zero-filled memory. It must still be freed like any heap block.

Summary

  • Heap memory is requested at run time and lives until you free it. It's how you build data whose size or lifetime isn't known when you write the code.
  • malloc(bytes) returns uninitialized memory; calloc(count, size) returns zeroed memory and checks the size multiplication. Both return NULL on failure: always check.
  • Size allocations with count * sizeof *p, and don't cast the result in C.
  • realloc may move the block. Assign its result to a temporary, check for NULL, then update your pointer. realloc(NULL, n) is malloc(n); don't call it with size 0 (undefined in C23).
  • Free every block exactly once, with the exact pointer you were given, and set the pointer to NULL afterwards when it stays in scope.
  • Make ownership explicit: if a function returns heap memory, document that the caller must free it.

Next: Memory Errors, where you'll meet leaks, double frees and use-after-free bugs, and the tools that find them.