Reallocating Memory in C: Dynamic Memory Management
Learn how to manage dynamic memory in C using the realloc()
function. Understand how memory reallocation works and how it helps resize previously allocated memory while preserving existing data.
C Reallocate Memory
Understanding Memory Reallocation
If the memory you've allocated is not enough, you can increase its size by reallocating it. Reallocation allows you to reserve more memory while keeping the existing data intact.
The realloc()
function is used to resize allocated memory, and it accepts two parameters:
Syntax
int *ptr2 = realloc(ptr1, size);
The first parameter is a pointer to the memory you're resizing, and the second parameter is the new size in bytes.
It attempts to resize the memory block at ptr1
. If successful, it will return the same memory address. If not, it will allocate memory at a new address and return that new pointer.
Important Considerations
- If
realloc()
returns a different memory address, the original address is no longer valid, so it's essential to assign the new pointer back to the original variable to avoid issues. - Error checking should be performed to handle memory allocation failures.
Example: Increasing Allocated Memory
Here’s an example of increasing the size of allocated memory using realloc()
:
int *ptr1, *ptr2, size;
// Allocate memory for four integers
size = 4 * sizeof(*ptr1);
ptr1 = malloc(size);
printf("%d bytes allocated at address %p \n", size, ptr1);
// Resize the memory to hold six integers
size = 6 * sizeof(*ptr1);
ptr2 = realloc(ptr1, size);
printf("%d bytes reallocated at address %p \n", size, ptr2);
NULL Pointer & Error Checking
The realloc()
function returns a NULL
pointer if it's unable to allocate more memory. While rare, it's important to check for this to ensure the program's stability.
Example: Checking for NULL
Pointer
int *ptr1, *ptr2;
// Allocate memory
ptr1 = malloc(4);
// Attempt to resize the memory
ptr2 = realloc(ptr1, 8);
// Check whether realloc is able to resize the memory or not
if (ptr2 == NULL) {
// If reallocation fails
printf("Failed. Unable to resize memory");
} else {
// If reallocation is successful
printf("Success. 8 bytes reallocated at address %p \n", ptr2);
ptr1 = ptr2; // Update ptr1 to point to the newly allocated memory
}
Always check for NULL
pointers when using malloc()
or realloc()
to ensure safe memory management in your programs.
Freeing Allocated Memory
Once you're done with the allocated memory, it's crucial to free it to prevent memory leaks. You can do this using the free()
function:
Example: Freeing Allocated Memory
// Free allocated memory
free(ptr1);
Releasing unused memory helps keep your program efficient and prevents unexpected behavior.