Back to Course
Pointers & Memory

Understanding realloc() function in C

What is realloc()?

realloc() is used to resize a previously allocated block of memory (from malloc() or calloc()) without losing the existing data.

Syntax

void* realloc(void *ptr, size_t newSize);

Example

int *arr = (int*) malloc(5 * sizeof(int));
arr = (int*) realloc(arr, 10 * sizeof(int));  // resize to hold 10 ints

Key Points

  • If there's enough contiguous space, memory is expanded in place; otherwise it's moved to a new location and the old data is copied.
  • If realloc() fails, it returns NULL and the original block remains untouched.
  • Always assign the result to a temporary pointer first to avoid memory leaks on failure.

Ready to master real-world C Programming development?

Learn C Programming hands-on with mentor-led, live sessions.

Explore Course