C 라이브러리 메모리 할당 함수 void *realloc(void *ptr, size_t size)는 이전에 malloc 또는 calloc에 대한 호출로 할당되었던 ptr이 가리키는 메모리 블록의 크기를 조정하려고 시도합니다.
메모리 할당 기능
메모리는 아래에 설명된 대로 두 가지 방법으로 할당할 수 있습니다. -

컴파일 타임에 메모리가 할당되면 실행 중에는 변경할 수 없습니다. 메모리가 부족하거나 낭비되는 문제가 있습니다.
솔루션은 프로그램 실행 중 사용자의 요구 사항에 따라 동적으로 메모리를 생성하는 것입니다.
동적 메모리 관리에 사용되는 표준 라이브러리 함수는 다음과 같습니다. -
- malloc( )
- 호출()
- 실제 할당( )
- 무료( )
realloc( ) 함수
-
이미 할당된 메모리를 재할당하는 데 사용됩니다.
-
할당된 메모리를 줄이거나 늘릴 수 있습니다.
-
재할당된 메모리의 기본 주소를 가리키는 void 포인터를 반환합니다.
realloc() 함수의 구문은 다음과 같습니다 -
Free void *realloc (pointer, newsize);
예시
다음 예제는 realloc() 함수의 사용법을 보여줍니다.
int *ptr; ptr = (int * ) malloc (1000);// we can use calloc also - - - - - - - - - ptr = (int * ) realloc (ptr, 500); - - - - - - ptr = (int * ) realloc (ptr, 1500);
예시
아래는 realloc() 함수를 사용하는 C 프로그램입니다 -
#include<stdio.h>
#include<stdlib.h>
int main(){
int *ptr, i, num;
printf("array size is 5\n");
ptr = (int*)calloc(5, sizeof(int));
if(ptr==NULL){
printf("Memory allocation failed");
exit(1); // exit the program
}
for(i = 0; i < 5; i++){
printf("enter number at %d: ", i);
scanf("%d", ptr+i);
}
printf("\nLet's increase the array size to 7\n ");
ptr = (int*)realloc(ptr, 7 * sizeof(int));
if(ptr==NULL){
printf("Memory allocation failed");
exit(1); // exit the program
}
printf("\n enter 2 more integers\n\n");
for(i = 5; i < 7; i++){
printf("Enter element number at %d: ", i);
scanf("%d", ptr+i);
}
printf("\n result array is: \n\n");
for(i = 0; i < 7; i++){
printf("%d ", *(ptr+i) );
}
return 0;
} 출력
위의 프로그램을 실행하면 다음과 같은 결과가 나온다 -
array size is 5 enter number at 0: 23 enter number at 1: 12 enter number at 2: 45 enter number at 3: 67 enter number at 4: 20 Let's increase the array size to 7 enter 2 more integers Enter element number at 5: 90 Enter element number at 6: 60 result array is: 23 12 45 67 20 90 60