← Back to C Course | Chapter 9: Memory Management | Lesson 5 of 8

C realloc()

Introduction to realloc()

This is the tool of choice when you don't know an array's final size upfront -- for example, reading an unknown number of lines from a file and growing a dynamic array to fit as you go, doubling its capacity each time it fills up.

Example: Introduction to realloc()

c
#include <stdio.h>
#include <stdlib.h>
int main() {
	int *arr = malloc(2 * sizeof(int));
	arr = realloc(arr, 4 * sizeof(int));
	arr[3] = 99;
	printf("%d", arr[3]);
	free(arr);
	return 0;
}

Expanding Allocated Memory

Because the system may need to find a larger contiguous free block elsewhere in memory, realloc() can change the pointer's actual address -- any old pointers or references into the original block become invalid after a successful call.

Example: Expanding Allocated Memory

c
#include <stdio.h>
#include <stdlib.h>
int main() {
	int *arr = malloc(2 * sizeof(int));
	arr[0] = 1; arr[1] = 2;
	arr = realloc(arr, 5 * sizeof(int));
	printf("%d", arr[0]);
	free(arr);
	return 0;
}

Shrinking Allocated Memory

The bytes beyond the new smaller size are discarded, but unlike freeing and reallocating from scratch, shrinking in place (when possible) avoids the overhead of copying the remaining data to a new location.

Example: Shrinking Allocated Memory

c
#include <stdio.h>
#include <stdlib.h>
int main() {
	int *arr = malloc(5 * sizeof(int));
	arr = realloc(arr, 2 * sizeof(int));
	printf("%zu bytes", 2 * sizeof(int));
	free(arr);
	return 0;
}

Handling realloc() failures safely

This failure behavior is exactly why you should never write ptr = realloc(ptr, newSize) directly -- if it fails and returns NULL, you've just overwritten your only reference to the original valid block, causing a memory leak.

Example: Handling realloc() failures safely

c
#include <stdio.h>
#include <stdlib.h>
int main() {
	int *arr = malloc(2 * sizeof(int));
	int *temp = realloc(arr, 4 * sizeof(int));
	if (temp != NULL) {
		arr = temp;
	}
	printf("%d", arr != NULL);
	free(arr);
	return 0;
}

Best practices with realloc()

Since each reallocation potentially involves copying the entire block's contents to a new address, growing an array one element at a time in a loop is much slower than growing it in larger chunks (like doubling capacity) less often.

Example: Best practices with realloc()

c
#include <stdio.h>
#include <stdlib.h>
int main() {
	int capacity = 2;
	int *arr = malloc(capacity * sizeof(int));
	capacity *= 2;
	arr = realloc(arr, capacity * sizeof(int));
	printf("%d", capacity);
	free(arr);
	return 0;
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.