C Reallocate Memory

C Tutorial

C Reallocate Memory realloc()?

In C Reallocate Memory The function realloc() is used to change the size of memory that was allocated using malloc() or calloc().

It can:

  • Increase the memory block size

  • Decrease the memory block size

  • Move the memory block to a new location (if needed)


📌 Syntax

pointer = realloc(pointer, new_size);

Where:

  • pointer → existing allocated memory

  • new_size → new required size in bytes


🧠 Important Behavior Notes

ActionBehavior
Increase sizeKeeps previous data and adds new space (uninitialized).
Decrease sizeKeeps only the data that fits.
Memory moveIf resizing requires a new block, old data is copied automatically.
FailureReturns NULL — original pointer remains unchanged.

🔍 Example: Expanding an Array Dynamically


 

Output:

10 20 30 40 50

❗ Safe Usage of realloc() (Recommended Method)

To avoid memory loss if realloc() fails:


📍 Example: Safe Reallocation



🧹 Remember to Free Memory

Always call:

free(arr);

when you are done using dynamically allocated memory.


🧾 Key Points to Remember

  • realloc() resizes memory previously allocated with malloc() or calloc().

  • It preserves existing data automatically.

  • It can move memory to a new location if needed.

  • Always check if realloc() returns NULL before assigning.

  • Always free() memory after use.

You may also like...