我有意删除结构的释放,并想了解valgrind如何计算内存泄漏。valgrind如何计算我的示例内存泄漏?
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
struct Person{
char *name;
int age;
int height;
int weight;
};
struct Person *Person_create(char *name, int age, int height, int weight){
struct Person *who = malloc(sizeof(struct Person));
assert(who != NULL);
who->name = strdup(name);
who->age = age;
who->height = height;
who->weight = weight;
return who;
}
void Person_destroy(struct Person *who){
assert(who != NULL);
free(who->name);
free(who);
}
void Person_print(struct Person *who){
printf("Name: %s\n", who->name);
printf("\tAge: %d\n", who->age);
printf("\tHeight: %d\n", who->height);
printf("\tWeight: %d\n", who->weight);
}
int main(int argc, char *argv[]){
//make two people structures
struct Person *joe = Person_create("Joe Alex", 32, 64, 140);
struct Person *frank = Person_create("Frank Blank", 20, 72, 180);
//print them out and where they are in memory
printf("Joe is at memory location %p\n", joe);
Person_print(joe);
printf("Frank is at memory location %p\n", frank);
Person_print(frank);
//make everyone age 20 years and print them again
joe->age += 20;
joe->height -= 2;
joe->weight += 40;
Person_print(joe);
frank->age += 20;
frank->weight += 20;
Person_print(frank);
// Person_destroy(joe);
// Person_destroy(frank);
return 0;
}
Valgrind的输出:
==7687== HEAP SUMMARY:
==7687== in use at exit: 69 bytes in 4 blocks
==7687== total heap usage: 4 allocs, 0 frees, 69 bytes allocated
==7687==
==7687== 33 (24 direct, 9 indirect) bytes in 1 blocks are definitely lost in loss record 3 of 4
==7687== at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==7687== by 0x40067B: Person_create (ex16.c:14)
==7687== by 0x4007B9: main (ex16.c:40)
==7687==
==7687== 36 (24 direct, 12 indirect) bytes in 1 blocks are definitely lost in loss record 4 of 4
==7687== at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==7687== by 0x40067B: Person_create (ex16.c:14)
==7687== by 0x4007D6: main (ex16.c:41)
==7687==
==7687== LEAK SUMMARY:
==7687== definitely lost: 48 bytes in 2 blocks
==7687== indirectly lost: 21 bytes in 2 blocks
==7687== possibly lost: 0 bytes in 0 blocks
==7687== still reachable: 0 bytes in 0 blocks
==7687== suppressed: 0 bytes in 0 blocks
==7687==
==7687== For counts of detected and suppressed errors, rerun with: -v
==7687== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
如果我不免费2个结构创建,泄漏应为4 * 4 * 2 = 32个字节。为什么字节总数泄漏48?
从uname - -a平台信息: Linux的mymachine上3.13.0-43泛型#72,Ubuntu的SMP周一12月8日19时35分06秒UTC 2014 x86_64的x86_64的x86_64的GNU/Linux的
感谢您的提醒。我在更新中指定了它。 – drdot
@dannycrane:然后指针肯定是64位宽,并且在结构的末尾有填充。查看更新后的答案。 – NPE
为什么最后需要填充? – drdot