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

pointer = realloc(pointer, new_size);

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

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

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

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

// Resize to store 5 integers
arr = (int*) realloc(arr, 5 * sizeof(int));

arr[3] = 40;
arr[4] = 50;

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

free(arr);
return 0;
}

Output:

10 20 30 40 50

โ— Safe Usage of realloc() (Recommended Method)

To avoid memory loss if realloc() fails:

int *temp = realloc(arr, new_size);
if (temp != NULL) {
arr = temp;
} else {
printf("Reallocation failed!\n");
}

๐Ÿ“ Example: Safe Reallocation

int *temp = realloc(arr, 100 * sizeof(int));
if(temp == NULL) {
printf("Error: Could not reallocate memory.\n");
return 1;
}
arr = temp;

๐Ÿงน 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.

CodeCapsule

Sanjit Sinha โ€” Web Developer | PHP โ€ข Laravel โ€ข CodeIgniter โ€ข MySQL โ€ข Bootstrap Founder, CodeCapsule โ€” Student projects & practical coding guides. Email: info@codecapsule.in โ€ข Website: CodeCapsule.in

You may also like...

Leave a Reply

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