반응형
realloc(3)
#include <stdlib.h>
void *realloc(void *ptr, size_t size);
malloc(3) / calloc(3) / realloc(3)으로 할당된 메모리의 크기를 재할당합니다. 기할당된 메모리(ptr)에 쓰여진 데이터는 재할당된 메모리 영역에 복제를 하고, 기존에 할당된 영역은 free(3)합니다. 또한 추가로 할당된 영역은 초기화되지 않습니다.
ptr이 NULL이면 malloc()함수와 같이 동작합니다.
size가 0이고 ptr이 NULL이 아니면 free(ptr)을 한 것과 같습니다.
파라미터
ptr
- malloc(3), calloc(3), realloc(3)으로 할당한 heap memory pointer
ptr이 NULL이면 malloc(3)함수 같습니다.
size
- 재할당하려는 크기(byte수)
size가 0이면 free(3)함수와 같습니다.
RETURN
NULL
- memory 재할당에 실패하였습니다.
NULL이 아닌 경우
- 정상적으로 메모리가 재할당되었습니다.
return type이 void *이므로 적절한 type casting을 하여 pointer 변수에 대입해야 합니다.
대체로 ptr 변수에 다시 대입합니다.
활용 예제
Sample
#include <stdio.h>
#include <stdlib.h>
......
int main(int argc, char *argv[])
{
int *ptr;
int size = 10000;
......
/* memory를 할당합니다. */
if((ptr = (int *)malloc(size) == NULL) {
fprintf(stderr, "malloc error.\n");
return 1;
}
......
/* 만약 크기를 더 늘려야 하는 경우 */
size += 10000;
if((ptr = (int *)realloc(ptr, size)) == NULL) {
fprintf(stderr, "realloc error.\n");
return 1;
}
......
/* memory를 해제합니다. */
free(ptr);
/*
free후에는 될 수 있으면 NULL을 대입하여 혹시라도 두 번 free하는 것을 방지하는 것이 좋습니다.
free한 메모리에 대해서 또 free하게 되면 coredump 비정상 종료될 수 있습니다.
*/
ptr = NULL;
return 0;
}
see also : memory 관련 함수
반응형
'C언어 header > stdlib.h' 카테고리의 다른 글
system(3) - 명령어를 실행하기 : fork(2) + execl(3) (0) | 2019.10.04 |
---|---|
realpath(3) - 절대 path로 변환하는 함수 (0) | 2019.09.25 |
calloc(3) - 메모리 할당 및 초기화 수행 (0) | 2019.09.24 |
free(3) - 할당된 heap 메모리 해제 (0) | 2019.09.24 |
malloc(3) - heap memory 할당하기 (0) | 2019.09.24 |