C Reallocate Memory

✅ 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
Where:
pointer→ existing allocated memorynew_size→ new required size in bytes
🧠 Important Behavior Notes
| Action | Behavior |
|---|---|
| Increase size | Keeps previous data and adds new space (uninitialized). |
| Decrease size | Keeps only the data that fits. |
| Memory move | If resizing requires a new block, old data is copied automatically. |
| Failure | Returns NULL — original pointer remains unchanged. |
🔍 Example: Expanding an Array Dynamically
Output:
❗ Safe Usage of realloc() (Recommended Method)
To avoid memory loss if realloc() fails:
📍 Example: Safe Reallocation
🧹 Remember to Free Memory
Always call:
when you are done using dynamically allocated memory.
🧾 Key Points to Remember
realloc()resizes memory previously allocated withmalloc()orcalloc().It preserves existing data automatically.
It can move memory to a new location if needed.
Always check if
realloc()returnsNULLbefore assigning.Always
free()memory after use.
