realloc() and free() in C
You allocated room for 10 items, and now the 11th arrives. Do you start over? No. realloc() resizes an existing block and keeps your data. And when you're done, free() gives the memory back.
In this lesson you will grow and shrink memory with realloc, learn the safe pattern that prevents losing your data, and learn the rules of free: when it's needed, what free(NULL) does, and why freeing twice is dangerous.
What You Will Learn
- What realloc does and its syntax.
- How realloc keeps (and moves) your data.
- The safe way to call realloc.
- Special cases: realloc(NULL, n).
- What free does and its rules.
- Double free and use-after-free.
realloc() and free() Explained
Exam definition: realloc(ptr, new_size) changes the size of a previously allocated block to new_size bytes, keeping the old contents (up to the smaller of the old and new sizes). It may move the block and returns the new address, or NULL on failure (the old block is then unchanged). free(ptr) releases a block allocated by malloc, calloc or realloc.
Memory trick: realloc is shifting house when the family grows: if the flat next door is free, you just knock down a wall (same address). If not, you move to a bigger flat, carry all your things along, and give back the old keys (new address). free = handing the keys back to the owner.
Syntax of realloc() and free()
void *realloc(void *ptr, size_t new_size);
void free(void *ptr);
/* SAFE pattern: never assign realloc's result straight to your only pointer */
int *tmp = realloc(p, new_count * sizeof *p);
if (tmp == NULL)
{
/* p is still valid and still holds the old data */
}
else
{
p = tmp;
}
free(p);
p = NULL;
Why the temp pointer?
If you write p = realloc(p, ...) and realloc fails, it returns NULL. Now p is NULL, and the old block, which is still allocated, has no pointer to it: a memory leak and lost data.
How realloc behaves
| Call | Effect |
|---|---|
realloc(p, bigger) | Grows the block; old data kept; new part is uninitialized; may move |
realloc(p, smaller) | Shrinks; data beyond the new size is lost |
realloc(NULL, n) | Same as malloc(n) |
| Failure | Returns NULL; old block untouched |
Before: p -> [10][20][30] (3 ints)
realloc(p, 5 * sizeof(int)):
Case A (room next to it): p -> [10][20][30][??][??] same address
Case B (no room): new -> [10][20][30][??][??] data copied,
old block freed automatically, address changes
Example 1: Growing and Shrinking an Array
#include <stdio.h>
#include <stdlib.h>
void show(const char *label, const int *a, int n)
{
int i;
printf("%-14s:", label);
for (i = 0; i < n; i++)
printf(" %d", a[i]);
printf("\n");
}
int main(void)
{
int n = 3, i;
int *a = malloc(n * sizeof *a);
int *tmp;
if (a == NULL)
return 1;
for (i = 0; i < n; i++)
a[i] = (i + 1) * 10;
show("Start (3)", a, n);
tmp = realloc(a, 6 * sizeof *a); /* grow to 6 */
if (tmp == NULL) { free(a); return 1; }
a = tmp;
for (i = n; i < 6; i++) /* new part is uninitialized */
a[i] = (i + 1) * 10;
n = 6;
show("Grown (6)", a, n);
tmp = realloc(a, 2 * sizeof *a); /* shrink to 2 */
if (tmp == NULL) { free(a); return 1; }
a = tmp;
n = 2;
show("Shrunk (2)", a, n);
free(a);
a = NULL;
return 0;
}
Output
Start (3) : 10 20 30 Grown (6) : 10 20 30 40 50 60 Shrunk (2) : 10 20
Code Explanation
- The first three values survive the resize: realloc copies the old data if it has to move the block.
- The new elements (index 3–5) are not initialized, so we fill them ourselves.
- Each realloc result goes into
tmpfirst. Only after checking for NULL do we updatea. - Shrinking to 2 keeps only the first two values.
- One final
free(a)releases whatever blockapoints to now. We never free the old addresses ourselves; realloc handled that.
Rules of free()
- Free only pointers returned by malloc, calloc or realloc. Never free a normal array or a local variable's address.
- Free each block exactly once. Freeing twice (double free) can crash or corrupt the heap.
free(NULL)is safe and does nothing. That's why settingp = NULLafter free protects you from double free.- After free, the pointer still holds the old address (dangling). Don't use it.
- Pass the start of the block. Freeing
p + 1is undefined behaviour. - free doesn't erase the data or change the pointer; it just tells the system the block is available again.
Example 2: Reading Any Number of Values (Doubling Capacity)
A program doesn't know how many marks will be entered. It starts small and doubles the capacity with realloc whenever it fills up. Input ends with −1.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int capacity = 2, count = 0, value, i, total = 0;
int *marks = malloc(capacity * sizeof *marks);
int *tmp;
if (marks == NULL)
return 1;
printf("Enter marks (-1 to stop): ");
while (scanf("%d", &value) == 1 && value != -1)
{
if (count == capacity) /* full: double it */
{
capacity *= 2;
tmp = realloc(marks, capacity * sizeof *marks);
if (tmp == NULL)
{
free(marks);
return 1;
}
marks = tmp;
printf("[grew to %d] ", capacity);
}
marks[count++] = value;
}
for (i = 0; i < count; i++)
total += marks[i];
printf("\n%d marks stored, average %.2f\n", count, (float) total / count);
free(marks);
marks = NULL;
free(marks); /* free(NULL) is harmless */
return 0;
}
Output
Enter marks (-1 to stop): 45 78 62 90 55 81 -1 [grew to 4] [grew to 8] 6 marks stored, average 68.50
- Capacity goes 2 → 4 → 8. Doubling means only a few reallocs, even for thousands of values.
- The second
free(marks)is harmless only because we set marks to NULL first. Without that line, it would be a double free. - (On screen, the typed numbers appear first; the "[grew to…]" notes print as the program processes them.)
Important Points to Remember
- realloc(ptr, new_size) resizes and keeps old data.
- It may move the block: always use the returned pointer.
- Use a temp pointer; on failure the old block is still valid.
- Newly added space is uninitialized.
- realloc(NULL, n) = malloc(n).
- Free each block once; free(NULL) is safe; set p = NULL after free.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
p = realloc(p, n); | On failure: leak + lost data | Use a temp pointer |
| Using the old pointer after realloc | Dangling if the block moved | Use the returned pointer |
Calling free twice | Double free: crash/heap corruption | p = NULL after free |
free(arr) for int arr[10] | Undefined behaviour | Only free heap memory |
| Assuming new realloc space is 0 | Garbage values | Initialize the new part |
realloc() and free() Practice Questions
- What does realloc do to the old data when growing a block?
- Why should realloc's result be stored in a temporary pointer?
- What is
realloc(NULL, 40)equivalent to? - What happens if you call free on the same pointer twice? How do you prevent it?
- Can you free an array declared as
int a[5];?
Show answers
- It keeps it (copying it to the new place if the block moves).
- If realloc fails it returns NULL; assigning directly would lose the only pointer to the still-allocated old block.
malloc(40).- Double free: undefined behaviour (crash or heap corruption). Set the pointer to NULL after freeing.
- No, only memory from malloc/calloc/realloc can be freed.
Coding Exercise
Start with a malloc'd string holding "Hello". Use realloc to make room and append ", World!" with strcat. Print the result and its length, then free it.
Show solution
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
const char *extra = ", World!";
char *s = malloc(strlen("Hello") + 1);
char *tmp;
if (s == NULL)
return 1;
strcpy(s, "Hello");
tmp = realloc(s, strlen(s) + strlen(extra) + 1);
if (tmp == NULL)
{
free(s);
return 1;
}
s = tmp;
strcat(s, extra);
printf("%s (%zu chars)\n", s, strlen(s));
free(s);
return 0;
}
Hello, World! (13 chars)
Quick Quiz: realloc() and free() (MCQ)
-
realloc is used to:
A) Free memory B) Resize allocated memory C) Zero memory D) Copy strings
-
If realloc fails, the old block is:
A) Freed B) Unchanged and still valid C) Zeroed D) Moved
-
free(NULL):A) Crashes B) Does nothing C) Frees all memory D) Returns −1
-
realloc(NULL, size)behaves like:A) free B) calloc C) malloc D) An error
-
Freeing the same block twice is called:
A) Memory leak B) Double free C) Wild pointer D) Buffer overflow
Show answers
- B: resize.
- B: unchanged and still valid.
- B: does nothing.
- C: malloc.
- B: double free.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| realloc | Resize, keeps old data, may move |
|---|---|
| Safe use | tmp = realloc(p, n); if (tmp) p = tmp; |
| On failure | Returns NULL, old block still valid |
| realloc(NULL, n) | = malloc(n) |
| New space | Uninitialized |
| free(NULL) | Safe, does nothing |
| After free | Set p = NULL |
Frequently asked questions
- What does realloc do?
- It changes the size of an allocated block, keeping the old data, possibly at a new address.
- Why not write p = realloc(p, n)?
- If realloc fails it returns NULL, and you lose the only pointer to the old block (memory leak).
- What is a double free?
- Calling free twice on the same block; it can crash or corrupt the heap. Prevent it by setting the pointer to NULL.
Remember
- realloc = shifting house: same flat if possible, else move with your things.
- Temp pointer for realloc, NULL after free.
Next Topic
Next lesson: Memory Leaks in C. You will see how forgotten free() calls cause memory leaks and how to prevent them.