2012-12-05 2 views
0

가능한 중복 :
How can I get the size of an array from a pointer in C?
How can I get the size of a memory block allocated using malloc()?프로그램에 할당 된 메모리를 찾고 계십니까?

void func(int *p) 
{ 
     // Add code to print MEMORY SIZE which is pointed by pointer p. 
} 
int main() 
{ 
     int *p = (int *) malloc(10 * sizeof(int)); 
     func(p); 
} 

우리가 어떻게 (FUNC 메모리 포인터 P에서 메모리 크기를 찾을 수 있습니다)?

+0

malloc (10)은 malloc (10 * sizeof (int))이어야합니다. –

답변

2

C에서 이식 할 수 없으므로 어디에도 저장되지 않을 수 있습니다. malloc()은 요청한 것보다 훨씬 큰 지역을 예약 할 수 있으며 요청한 양에 대한 정보를 저장할 수는 없습니다.

당신에게 하나는 표준 크기를 사용할 필요가 같은 malloc(ARRAY_LEN * sizeof(int)) 또는 malloc(sizeof mystruct), 같은하거나 포인터로 주위의 정보를 전달해야합니다

struct integers { 
    size_t count; 
    int *p; 
}; 

void fun(integers ints) { 
    // use ints.count to find out how many items we have 
} 

int main() { 
    struct integers ints; 
    ints.count = 10; 
    ints.p = malloc(ints.count * sizeof(int)); 
    fun(ints); 
} 
0

A에 대한 할당 된 메모리를 찾을 수없는 붙박이 논리가 없다 바늘. 브라이언이 대답에 언급 한대로 자신의 방법을 구현해야합니다.

예, 리눅스에서 valgrind와 같은 도구를 사용하여 유출 된 메모리를 찾을 수 있습니다. solaris에는 libumem.so라는 라이브러리가 있습니다.이 라이브러리에는 프로세스가 실행 중일 때 누출되는 메모리 양을 알려주는 findleaks라는 함수가 있습니다.

관련 문제