편집 기록

편집 기록
  • 프로필 엽토군님의 편집
    날짜2019.11.14

    C realloc() 질문입니다.


    #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가 아닌 쓰레기값이나 다른 값이 나와야 하는거 아닌가요?

  • 프로필 알 수 없는 사용자님의 편집
    날짜2019.11.08

    C realloc() 질문입니다.


    #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가 아닌 쓰레기값이나 다른 값이 나와야 하는거 아닌가요?