C realloc() 질문입니다.

조회수 507회
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <string.h>
#include <time.h>

int main()
{
    unsigned char *test;
    int i;
    test = (unsigned char*)malloc(5);

    for(i = 0; i < 5; i++)
    {
        test[i] = 0x11;
    }
     for(i = 0; i < 5; i++)
    {
        printf("%d. 0x%x\n ", i, test[i]);
    }

    printf("\n");


    test = (unsigned char*)realloc(test,3);

     for(i = 3; i < 5; i++)
    {
        test[i] =0xff;

    }

    for(i = 0; i < 5; i++)
    {
        printf("%d. 0x%x \n", i, test[i]);
    }

    free(test);

    return 0;
}

처음에 malloc()로 5만큼 할당을 받은후 realloc()로 다시 3으로 축소를 시켰는데 test[4]까지 접근이 되는 이유를 알고싶습니다. test[2]까지만 값을 출력해주고 그 이후부터는 0xff가 아닌 쓰레기값이나 다른 값이 나와야 하는거 아닌가요?

  • realloc 함수는 보통 확장시에 사용합니다. realloc 같은 경우는 구현도 제각각 이므로 구현된 코드를 직접보는 편이 낫습니다. 또한 질문과 같은 상황이라면 복사후 free 하고 다시 malloc 하는 편이 나아보입니다. 정영훈 2019.11.8 05:05

1 답변

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)