If the allocated memory is insufficient, you can reallocate it to increase its size.
Reallocating reserves a different amount of memory, typically larger, while retaining the data stored within it.
You can adjust the size of allocated memory using the realloc() function.
The realloc() function requires two parameters:
int *ptr2 = realloc(ptr1, size); |
The realloc() function attempts to resize the memory at the address specified by ptr1 and returns the same address if successful. If resizing at the current address is not possible, it allocates memory at a different address and returns this new address instead.
Important to note: If realloc() returns a different memory address, the memory previously reserved at the original address is no longer guaranteed and should not be accessed. To ensure safety, after reallocation, it’s advisable to assign the new pointer to the previous variable, preventing inadvertent use of the old pointer. |
Expand the size of allocated memory.
int *ptr1, *ptr2, size;
// Allocate memory for four integers printf(“%d bytes allocated at address %p \n”, size, ptr1); // Resize the memory to hold six integers printf(“%d bytes reallocated at address %p \n”, size, ptr2); |
The realloc() function returns a NULL pointer if it fails to allocate more memory, although such occurrences are rare. However, it’s prudent to consider this possibility when aiming for robust code.
The subsequent example demonstrates a check for realloc()’s success by inspecting for a NULL pointer.
Verify the existence of a NULL pointer.
int *ptr1, *ptr2;
// Allocate memory // Attempt to resize the memory // Check whether realloc is able to resize the memory or not |
Remember to incorporate error checking (e.g., if pointer == NULL) when allocating memory. Additionally, it’s crucial to release allocated memory once it’s no longer needed. This practice not only ensures expected program behavior but also enhances maintainability and efficiency. |
To release memory, employ the free() function.
Release allocated memory.
// Free allocated memory free(ptr1); |
In the next chapter, you’ll delve deeper into the process of freeing allocated memory and understand its importance.