Skip to main content

Resizing Memory

Resizing Memory

  • Resizing memory in C is typically done using the realloc function, which is used to change the size of an already allocated memory block.

Things to be considered using realloc:

  • It's important to note that realloc may move the memory block to a different location if necessary.

  • If this happens, any pointers to the original memory block become invalid, so we need to make sure to update any pointers to the new memory location.

-It's also important to properly manage dynamically allocated memory to avoid memory leaks. Always make sure to deallocate memory using the free function when it's no longer needed.

Example

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

int main() {
// Allocate memory for an array of 5 integers
int* dynamicArray = malloc(5 * sizeof(int));

if (dynamicArray == NULL) {
printf("Failed to allocate memory.\n");
return 1; // Error handling
}

// Use the dynamically allocated memory

// Resize the array to 10 integers
dynamicArray = realloc(dynamicArray, 10 * sizeof(int));

if (dynamicArray == NULL) {
printf("Failed to reallocate memory.\n");
return 1; // Error handling
}

// Use the resized memory block

// Deallocate the memory when done
free(dynamicArray);

return 0;
}

Explanation:

  • Here, we first allocate memory for an array of 5 integers using the malloc function.
  • Then, we use the realloc function to resize the memory block to an array of 10 integers.
  • If the reallocation is successful, the pointer returned by realloc points to the beginning of the new memory block.
  • If it fails, it returns NULL, in which case we need to handle the error.