반응형

소스코드

- malloc을 이용해서, 길이 1024 메모리를 생성한다. realloc으로 해당 메모리의 크기를 128로 늘린다.

- 이후, 해당 메모리의 길이를 확인해본다.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    int *ptr;
    int size = 1024;

	// 1024크기 만큼 동적할당
    if ((ptr = (int *)malloc(size)) == NULL) {
        printf("malloc error\n");
        return 1;
    }

	// 128크기 만큼 추가 동적할당
    size += 128;
    if ((ptr = (int *)realloc(ptr, size)) == NULL) {
        printf("realloc error\n");
        return 1;
    }

	// 동적할당 메모리 길이 구하기
    size_t num_size = malloc_usable_size(ptr);
    printf("size = %d\n", num_size);

    free(ptr);

    ptr = NULL;
    return 0;
}

 

 

출력화면

size = 1160

 

설명

메모리 총 크기가 실제 할당한 크기보다 다른 이유는, CPU 바이트 순서 및 정렬에 따라 요청된 크기보다 클수 있음.

(출처: https://changun516.tistory.com/89 [하루의 쉼터])

 

 

참고자료

동적할당 메모리 사이즈 구하는 소스코드

#include <malloc.h>

inline size_t sizeof_malloc( void* p )
{
#if _MSC_VER
    return  _msize( p );
#else
#if __GNUC__
    return  malloc_usable_size( p );
#else
#if __APPLE__
    return  malloc_good_size( p );
#endif
#endif
#endif
}
반응형