CodeBlanks Logo Icon CodeBlanks

Resize with realloc

  • C course
  • Intermediate
  • Lesson 8/116
  • 5 min

Learn to resize an array with realloc.

Resizing with realloc

realloc grows or shrinks a previously allocated block. Signature: void *realloc(void *ptr, size_t new_size);.

Example: arr = realloc(arr, 5 * sizeof(int));. Old content is preserved; new elements are uninitialized. One key point: if realloc fails it returns NULL and the old memory is still valid. So writing arr = realloc(arr, ...) directly is risky; on failure you lose the old address. The safe pattern is to use a temporary pointer.

The safe realloc pattern

Safe realloc uses a temporary pointer. First call tmp = realloc(arr, new_size); if tmp is not NULL, do arr = tmp.

Example: int *tmp = realloc(arr, 5 * sizeof(int)); if (tmp) arr = tmp;. In this pattern, even if realloc fails, arr keeps the old address and free(arr) still works. If the new size is smaller than the old content, the overflow part is lost. Memory management needs care; this pattern is standard for large allocations.

Practice Grow an array with realloc

Allocate a two-element array with int *arr = malloc(2 * sizeof(int));. Assign arr[0] = 1; arr[1] = 2;. Use the safe realloc pattern to grow it to 4 elements: int *tmp = realloc(arr, 4 * sizeof(int)); if (tmp) arr = tmp;. Assign 3 and 4 to the new two elements. Print all four with printf("%d ", arr[i]) in a for loop, then printf("\n"). Free with free(arr);.

Starter code

main.c
#include <stdio.h>
#include <stdlib.h>

// Allocate two elements, assign 1, 2
// Grow to four with safe realloc
// Assign 3, 4, print and free

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int *arr = malloc(2 * sizeof(int));
    arr[0] = 1;
    arr[1] = 2;
    int *tmp = realloc(arr, 4 * sizeof(int));
    if (tmp) arr = tmp;
    arr[2] = 3;
    arr[3] = 4;
    for (int i = 0; i < 4; i++) printf("%d ", arr[i]);
    printf("\n");
    free(arr);
    return 0;
}

Expected output

1 2 3 4

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the realloc behaviors

Term Meaning
realloc(NULL, n) Behaves like malloc
realloc(ptr, 0) Behaves like free
realloc(ptr, larger) Grows
realloc fails Old block valid

2 What happens if realloc returns NULL?

  • Old memory is freed
  • The program crashes
  • Old memory is still valid Correct answer
  • arr becomes NULL

Explanation: On realloc failure the old block is not freed; it stays valid.

3 Safe realloc pattern

Question
int *tmp = ____(arr, 5 * sizeof(int));
if (tmp) arr = tmp;
Answer
int *tmp = realloc(arr, 5 * sizeof(int));
if (tmp) arr = tmp;

Explanation: realloc resizes an existing block.

All lessons in Intermediate