Dynamic Memory Allocation Using realloc()

What is relloc() ?

relloc() function is used to change the size of the memory block without losing the old data.

syntax:
				
					void *realloc(void *ptr, size_t newSize);
				
			
dynacmic memory allocation

On failure, realloc return NULL

Example of malloc():
				
					int *ptr = (int *)malloc(sizeof(int));
				
			
Example of realloc():
				
					ptr = (int *)realloc(ptr, 2*sizeof(int));
				
			
  • This will allocate memory space of 2*sizeof(int).
  • Also, this function moves the contents of the old block to a new block and the data of the old block is not lost.
  • We may lose the data when the new size is smaller than the old size.
  • Newly allocated bytes are unitialised.
Example:
				
					#include<stdio.h>
#include<stdlib.h>
int main(){
	int i;
	int *ptr = (int *)malloc(2*sizeof(int));
	
	if(ptr == NULL){
		printf("Memory not available!");
		exit(1);
	}
	
	printf("Enter the two numbers: \n");
	for(i=0; i<2; i++){
		scanf("%d",ptr+i);
	}
	
	ptr = (int *)realloc(ptr, 4*sizeof(int));
	if(ptr == NULL){
		printf("Memory not available!");
		exit(1);
	}
	
	printf("Enter two more integer: \n");
	for(i=2; i<4; i++){
		scanf("%d",ptr+i);
	}
	
	for(i=0; i<4; i++){
		printf("%d ",*(ptr+i));
	}
	return 0;
}
				
			
Output:
				
					Enter the two numbers:
1
2
Enter two more integer:
3
4
1 2 3 4
				
			

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *