What is C realloc Resize Memory – Embedded C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course • Pointers • Dynamic Memory

C realloc Resize Memory

Master realloc in C: resize heap blocks safely, avoid leaks with the temporary-pointer pattern and handle moves in embedded C.

free c programming coursefree c tutorialembedded c programmingrealloc in c

What You Will Learn

  • What realloc in C does and what it guarantees
  • The safe temporary-pointer pattern that prevents leaks
  • Why pointers can dangle after a block moves
  • How to grow and shrink a buffer with a tested program
  • realloc cautions for embedded C programming

Prerequisites

  • Lectures on malloc and calloc in C
  • Pointer notation and array indexing
  • A GCC (or compatible) compiler

What Does realloc in C Do?

Sooner or later a program discovers that the block it allocated earlier is the wrong size. A log that was expected to hold four entries now needs eight, or a buffer sized for the worst case can be trimmed once the real length is known. realloc in C is the standard answer: it changes the size of an existing heap block while preserving the data already stored in it. It is the third function in this free C programming course’s dynamic memory family, and by far the one that is easiest to misuse.

Prototype to remember

void *realloc(void *ptr, size_t new_size); — returns a pointer to a block of new_size bytes whose first bytes equal those of the old block, or NULL on failure (in which case the old block is untouched).

Three behaviours define realloc, and you should be able to recite them:

  1. The old contents are kept, up to the smaller of the old and new sizes.
  2. If the block grows, the added bytes are uninitialised; realloc does not zero them.
  3. The returned address may differ from the one you passed in, because the allocator is free to move the data.

How realloc Works Behind the Scenes

The allocator first checks whether the bytes immediately after your block are free. If they are, it simply extends the block in place and returns the same address. If something else sits there, it finds a new block of the right size elsewhere, copies the old contents across, frees the old block and returns the new address. Shrinking normally happens in place, with the leftover tail returned to the free list.

Two ways realloc can grow a block

BEFOREaddr A: [10][20][30][40]neighbour: free space
IN PLACEaddr A: [10][20][30][40][??][??][??][??]same address returned
BEFOREaddr A: [10][20][30][40]neighbour: in use
MOVEDaddr A: freedaddr B: [10][20][30][40][??][??][??][??]new address returned

You cannot know in advance which case you will get, and the answer can change from run to run. This is why every pointer you keep into the old block, whether a copy of the base address or a pointer to one element, must be treated as invalid after a successful realloc.

The Safe realloc Pattern: Never Overwrite Your Only Pointer

Many tutorials show ptr = realloc(ptr, newsize); on a single line. That compact form hides a trap. If realloc fails it returns NULL, the assignment replaces your only pointer with NULL, and the original block, which is still perfectly valid and still holding your data, becomes unreachable. You have just created a memory leak and lost your data in one step. The remedy is a temporary pointer.

PatternOn successOn failure
p = realloc(p, n);Worksp becomes NULL, old block leaked, data lost
tmp = realloc(p, n); if (tmp) p = tmp;Worksp still valid, can free or keep using it

The program below grows a four-element log to eight elements and then shrinks it to three, using the safe pattern both times.

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

int main(void)
{
    size_t cap = 4;
    int *log = malloc(cap * sizeof *log);
    if (!log) return 1;

    for (size_t i = 0; i < cap; i++)
        log[i] = (int)(i + 1) * 10;                /* 10 20 30 40 */

    /* WRONG pattern:  log = realloc(log, ...)  loses the block on failure.
       RIGHT pattern: use a temporary pointer.                              */
    size_t new_cap = 8;
    int *tmp = realloc(log, new_cap * sizeof *log);
    if (tmp == NULL) {
        free(log);                                 /* old block still valid */
        return 1;
    }
    log = tmp;
    cap = new_cap;

    for (size_t i = 4; i < cap; i++)
        log[i] = (int)(i + 1) * 10;                /* new slots */

    printf("after grow  :");
    for (size_t i = 0; i < cap; i++) printf(" %d", log[i]);
    printf("\n");

    /* shrink: only the first 3 values survive */
    tmp = realloc(log, 3 * sizeof *log);
    if (tmp) log = tmp;

    printf("after shrink:");
    for (size_t i = 0; i < 3; i++) printf(" %d", log[i]);
    printf("\n");

    free(log);
    return 0;
}
gcc -std=c17 -Wall -Wextra -Wpedantic -o ep_realloc_grow ep_realloc_grow.c
./ep_realloc_grow

Expected output:

after grow  : 10 20 30 40 50 60 70 80
after shrink: 10 20 30

Walking through the program

  1. The first four slots receive 10, 20, 30, 40. This is the data that must survive the resize.
  2. realloc(log, new_cap * sizeof *log) asks for room for eight integers. The result goes into tmp, not log.
  3. On failure the code frees the still-valid old block and exits. On success log = tmp adopts the new address.
  4. Slots 4 to 7 are written before they are printed, because the new bytes are uninitialised.
  5. The shrink call keeps only the first three values, and again goes through tmp.

Special Cases of realloc You Should Know

CallBehaviourAdvice
realloc(NULL, n)Equivalent to malloc(n)Handy for growing a buffer that starts empty
realloc(p, 0)Implementation-defined in older standards; undefined behaviour in C23Do not use it to free memory; call free
realloc(p, same_size)Returns a valid block with the same contentsHarmless but pointless
Pointer not from malloc/calloc/reallocUndefined behaviourNever pass stack or static addresses
Pointer already freedUndefined behaviourSet pointers to NULL after free

Dangling Pointers After realloc

Suppose you save the address of the third element, int *third = &log[2];, and later call realloc. If the allocator moved the block, third still points into the old, freed region. Reading or writing through it is undefined behaviour and may appear to work for weeks. The fix is to store indexes instead of pointers whenever a container can grow, or to recompute the pointer from the base address after every resize.

size_t third_idx = 2;          /* index stays valid across realloc */
log = grow(log, 16);           /* may move the block */
int third_value = log[third_idx];

realloc in Embedded C Programming

On a microcontroller, realloc is the most fragmentation-prone function in the family. Each grow-and-move leaves a hole behind, and a heap of a few kilobytes can become too fragmented to satisfy a request even when plenty of total space is free. If you need a growable buffer on a small device, choose a sensible maximum capacity up front, grow by doubling instead of by one element at a time, and avoid resizing during time-critical work. When the worst case is bounded, a fixed array is simpler, faster and deterministic, which is exactly what a free embedded C course should teach you to prefer.

Common realloc Mistakes and Troubleshooting

  1. Using the one-line form and leaking on failure.
  2. Reading the new bytes before writing them.
  3. Keeping old pointers into a block that has moved.
  4. Growing one element at a time. Each call may copy the whole array, giving quadratic behaviour. Double the capacity instead.
  5. Computing the size without sizeof and requesting bytes instead of elements.
  6. Calling realloc on a pointer to the middle of a block. Only the exact address returned by the allocator is valid.

Test it

Build with gcc -g -fsanitize=address. If you accidentally use a pointer from before the resize, AddressSanitizer reports a heap-use-after-free pointing at both the bad access and the realloc that moved the block.

Best Practices Checklist

  • Always assign the result to a temporary and test it before replacing the original pointer.
  • Track capacity and length separately so you grow only when full.
  • Grow geometrically (double) to keep the total copying cost low.
  • Do not keep raw pointers into a resizable block across a resize.
  • Initialise the new region if the code might read it.

Quick Recap: realloc in C

The rules for realloc in C fit on one line: use a temporary pointer, check it, adopt it and forget every older pointer into the block. Good realloc in C code never reads the newly added bytes before writing them and grows capacity geometrically. In embedded projects, treat realloc in C as a tool for start-up code rather than for hot paths.

Summary and Key Takeaways

  • realloc resizes a heap block and preserves the old data up to the smaller size.
  • The address may change; failure returns NULL and leaves the old block valid.
  • Use a temporary pointer to avoid leaking on failure.
  • New bytes are uninitialised; old pointers into the block become invalid after a move.
  • On small embedded heaps, plan capacities up front to avoid fragmentation.

Conclusion

With malloc, calloc and realloc you can now create, zero and resize blocks. The final piece, covered in the next lecture, is giving memory back with free and avoiding the leaks and dangling pointers that appear when ownership is unclear. Experiment with the example by growing the log several times and printing the address after each step; you will see for yourself that the pointer sometimes changes and sometimes does not, which is the best possible reminder to always use the returned value.

Frequently Asked Questions

What does realloc do in C?

It changes the size of a previously allocated heap block, keeping the existing data, and returns a pointer to the resized block, which may be at a different address.

What happens to the old data when realloc grows a block?

It is preserved. The extra bytes added at the end are uninitialised.

What does realloc return on failure?

NULL. The original block is left unchanged and must still be freed, which is why you should not overwrite your only pointer with the result.

Can realloc move memory?

Yes. If the block cannot be extended in place, the allocator copies the data to a new location and frees the old one. Always use the returned pointer.

Is realloc(ptr, 0) the same as free(ptr)?

No. The result was implementation-defined and is undefined behaviour in C23. Call free explicitly.

Is realloc(NULL, n) valid?

Yes. It behaves like malloc(n).

Should I use realloc on microcontrollers?

Use it sparingly. It can fragment a small heap, so prefer fixed buffers or allocate the maximum once at start-up.

Finish the Dynamic Memory Chapter

Next up: free(), memory leaks and returning heap pointers from functions.

<div
💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →