C Programming
In this tutorial we will learn about realloc function to dynamically reallocate memory in C programming language.
We use the realloc function to change the memory size of the previously allocated memory space.
realloc
Following is the syntax of the realloc function.
ptr = realloc(ptr, new_size);
Where, ptr is a pointer pointing at the allocated memory location. new_size is the size of the new allocation.
ptr
new_size
Following are the points to note when using realloc function.
NULL
In the following code we are first allocating 6 bytes of memory space of type char using the malloc function.
char
malloc
Then we are taking 5 letters word from the user as input and saving it in the allocated memory space.
After that we are reallocating 9 bytes of memory space of type char using the realloc function.
Then, we are taking 8 letters word from the user as input and saving it in the newly reallocated memory space.
The last byte is used to store the NULL \0 character to mark the end of the string. So, 6 bytes space can hold 5 bytes text and similarly, 9 bytes will hold 8 bytes text.
\0
#include <stdio.h> #include <stdlib.h> int main(void) { // character pointer char *cptr = NULL; // allocate memory cptr = (char *) malloc (6 * sizeof(char)); // if failed if (cptr == NULL) { printf("Failed to allocate memory space. Terminating program..."); return -1; } // get some text printf("Enter 5 letters word: "); scanf("%s", cptr); // display printf("Word you entered: %s\n", cptr); // reallocate memory cptr = realloc(cptr, (9 * sizeof(char))); // if failed if (cptr == NULL) { printf("Failed to reallocate new memory space. Terminating program..."); return -1; } // content printf("\nContent of the allocated memory space after reallocation:\n"); printf("%s\n\n", cptr); // get some new text printf("Enter 8 letters word: "); scanf("%s", cptr); // display printf("Word you entered: %s\n", cptr); // free memory space free(cptr); return 0; }
Output:
Enter 5 letters word: hello Word you entered: hello Content of the allocated memory space after reallocation: hello Enter 8 letters word: computer Word you entered: computer
We can represent the allocated memory via malloc function as follows.
And we can show the reallocated memory via realloc function as follows.