In C, we can use the realloc()
function to resize previously allocated memory areas at a later time.
This function is included in the
<stdlib.h>
library.
The syntax of the function is as follows:
void *realloc(void *ptr, size_t size);
The function needs:
(void *ptr)
: A pointer that represents the pointer to the beginning of the memory area that you want to resize.(size_t size)
: The new size of the block in bytes, where size_t
is just an alias of unsigned int
, defined in the <stdlib.h>
library. The new block can be smaller or larger than the one that is being modified.The function returns a pointer to the beginning of the block of memory. If the block of memory cannot be allocated, the function will return a null
pointer.
Let’s see two examples:
The first one assumes that the size of the block to be reallocated is smaller than previously allocated.
The second one assumes that the size of the block to be reallocated is bigger than previously allocated.
The size of the block is smaller.
#include<stdio.h>#include<stdlib.h>int main(){int *ptr;//Here, we allocate memory for 40 integersptr = malloc(10 * sizeof(int));ptr[3] = -120;//We reallocate memory size to store 16 integersptr = realloc(ptr, 4 * sizeof(int));if(ptr == NULL) {exit(0);}// we can still see at address 3printf("%d", ptr[3]);return 0;}
The size of the block is bigger.
#include<stdio.h>#include<stdlib.h>int main(){int *ptr;//Here, we allocate memory for 40 integersptr = malloc(10 * sizeof(int));//We reallocate memory size to store 160 integersptr = realloc(ptr, 40 * sizeof(int));if(ptr == NULL) {exit(0);}ptr[100] = -120;printf("%d", ptr[100]);return 0;}