반응형

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 관련 함수

 

 

반응형
블로그 이미지

자연&사람

행복한 개발자 programmer since 1995.

,