C Lesson 22 – realloc and free | Dataplexa

realloc() and free() in C

In the previous lessons, you learned how to allocate memory using malloc() and calloc().

Now comes the most critical responsibility of a C programmer: managing memory correctly.

This lesson will teach you:

  • How to resize allocated memory
  • How to safely release memory
  • How to avoid dangerous memory mistakes

What Is realloc()?

realloc stands for re-allocation.

It is used when:

  • You need more memory than initially allocated
  • You want to reduce unused memory

Instead of creating new memory from scratch, realloc modifies existing memory.


Basic Syntax of realloc()


ptr = realloc(ptr, new_size);

Important rule:

  • The pointer passed to realloc must already be allocated

Example: Expanding Memory


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

int main() {
    int *arr = (int*) malloc(2 * sizeof(int));

    arr[0] = 10;
    arr[1] = 20;

    arr = realloc(arr, 4 * sizeof(int));

    arr[2] = 30;
    arr[3] = 40;

    for(int i = 0; i < 4; i++) {
        printf("%d ", arr[i]);
    }

    free(arr);
    return 0;
}

Explanation:

  • Initial memory holds 2 integers
  • realloc expands it to 4 integers
  • Old data is preserved

How realloc Works Internally

When realloc is called:

  • If adjacent memory is available → memory expands in place
  • If not → new memory is allocated
  • Old data is copied
  • Old memory is freed automatically

You don’t see this process — but it happens underneath.


Reducing Memory Size

realloc can also reduce memory size:


ptr = realloc(ptr, 2 * sizeof(int));

This frees extra unused memory.


What Is free()?

free() releases dynamically allocated memory back to the system.


free(ptr);

After calling free:

  • The memory is no longer valid
  • Using it causes undefined behavior

Best Practice After free()

Always reset pointer after freeing:


free(ptr);
ptr = NULL;

This prevents accidental reuse.


Common Memory Mistakes

  • Forgetting to call free()
  • Using memory after free()
  • Calling free() twice
  • Losing pointer reference

These mistakes cause memory leaks and crashes.


Real-World Analogy

Think of memory like a rented apartment:

  • malloc / calloc → rent apartment
  • realloc → upgrade to bigger apartment
  • free → vacate apartment

If you don’t vacate, rent keeps accumulating.


Mini Practice

  • Allocate memory for 2 integers
  • Expand it to 5 using realloc
  • Store values
  • Free memory safely

Quick Quiz

Q1. What does realloc do?

Resizes previously allocated memory.

Q2. Does realloc preserve old data?

Yes, if possible.

Q3. What happens if free() is not called?

Memory leak occurs.

Q4. Is it safe to use pointer after free()?

No.

Q5. Why set pointer to NULL after free()?

To avoid accidental reuse.