C Reallocate Memory
โ
What is realloc()?
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 memory -
new_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.
