Size of dynamically allocated memory can be changed by using realloc().
As per the C99 standard:
void *realloc(void *ptr, size_t size); |
realloc deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size. The contents of the new object is identical to that of the old object prior to deallocation, up to the lesser of the new and old sizes. Any bytes in the new object beyond the size of the old object have indeterminate values.
The point to note is that realloc() should only be used for dynamically allocated memory. If the memory is not dynamically allocated, then behavior is undefined.
For example, program 1 demonstrates incorrect use of realloc() and program 2 demonstrates correct use of realloc().
Program 1:
#include <stdio.h> #include <stdlib.h> int main() { int arr[2], i; int *ptr = arr; int *ptr_new; arr[0] = 10; arr[1] = 20; // incorrect use of new_ptr: undefined behaviour ptr_new = (int *)realloc(ptr, sizeof(int)*3); *(ptr_new + 2) = 30; for(i = 0; i < 3; i++) printf("%d ", *(ptr_new + i)); getchar(); return 0; } |
Output:
Undefined Behavior
Program 2:
#include <stdio.h> #include <stdlib.h> int main() { int *ptr = (int *)malloc(sizeof(int)*2); int i; int *ptr_new; *ptr = 10; *(ptr + 1) = 20; ptr_new = (int *)realloc(ptr, sizeof(int)*3); *(ptr_new + 2) = 30; for(i = 0; i < 3; i++) printf("%d ", *(ptr_new + i)); getchar(); return 0; } |
Output:
10 20 30
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
- Do not use sizeof for array parameters
- Can we use function on left side of an expression in C and C++?
- What is use of %n in printf() ?
- When do we use Initializer List in C++?
- Use of explicit keyword in C++
- How to use getline() in C++ when there are blank lines in input?
- Use of fflush(stdin) in C
- How to use POSIX semaphores in C language
- Use of & in scanf() but not in printf()
- Why strcpy and strncpy are not safe to use?
- Why to use fgets() over scanf() in C?
- Features and Use of Pointers in C/C++
- How can we use Comma operator in place of curly braces?
- Use of bool in C
- How to use make utility to build C projects?`
- gets() is risky to use!

