当我运行我的代码时,valgrind会发出此错误。
Invalid free() / delete / delete[] / realloc()
==7363== at 0x4C2A82E: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==7363== by 0x4009F8: main (in /home/arihant/ELF/elf)
==7363== Address 0x51f3fa0 is 0 bytes inside a block of size 16 free'd
==7363== at 0x4C2A82E: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==7363== by 0x4009B1: main (in /home/arihant/ELF/elf)
==7363==
==7363==
==7363== HEAP SUMMARY:
==7363== in use at exit: 160 bytes in 4 blocks
==7363== total heap usage: 448 allocs, 448 frees, 34,684 bytes allocated
==7363==
==7363== LEAK SUMMARY:
==7363== definitely lost: 160 bytes in 4 blocks
==7363== indirectly lost: 0 bytes in 0 blocks
==7363== possibly lost: 0 bytes in 0 blocks
==7363== still reachable: 0 bytes in 0 blocks
==7363== suppressed: 0 bytes in 0 blocks
==7363== Rerun with --leak-check=full to see details of leaked memory
==7363==
==7363== For counts of detected and suppressed errors, rerun with: -v
==7363== ERROR SUMMARY: 6 errors from 2 contexts (suppressed: 2 from 2)
为什么我会丢失160个字节,尽管alloc的数量和free相等
我的代码是
18 fp = fopen("output", "r");
19 obj_elf = (Elf32_Ehdr *)malloc(sizeof(Elf32_Ehdr));
20 fread(obj_elf, 1, sizeof(Elf32_Ehdr), fp);
21
22 if (argc < 2) {
23 print_menu();
24 free(obj_elf);
25 fclose(fp);
26 return 0;
27 }
28
29 if (argv[1][0] == '-') {
30 switch (argv[1][1]) {
31 case 'e':
32 elf_header(obj_elf); /*elf header function call*/
33 break;
34 case 's':
35 read_section_header(fp, obj_elf, obj_sect_hdr);
36 print_section_header(fp, obj_sect_hdr, obj_elf);
37
38 for (i = 0; i < obj_elf->e_shnum; i++) {
39 free(obj_sect_hdr[i]);
40 free(sec_name[i]);
41 }
42 break;
43 case 'S':
44 read_section_header(fp, obj_elf, obj_sect_hdr);
45 read_symbol_table(fp, obj_elf, obj_sect_hdr, obj_sym);
46 symbol_table(fp, obj_elf, obj_sect_hdr, obj_sym);
47
48 for (i = 0; i < obj_elf->e_shnum; i++) {
49 free(obj_sect_hdr[i]);
50 free(sec_name[i]);
51 }
52 for (i = 0; i < n_entries_sym_t; i++) {
53 free(obj_sym[i]);
54 free(symbol_name[i]);
55 }
56
在main函数中有很多free我怎么知道哪个free是无效的?
答案 0 :(得分:0)
您的答案位于输出的顶部:
Invalid free() / delete / delete[] / realloc()
==7363== at 0x4C2A82E: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==7363== by 0x4009F8: main (in /home/arihant/ELF/elf)
==7363== Address 0x51f3fa0 is 0 bytes inside a block of size 16 free'd
==7363== at 0x4C2A82E: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==7363== by 0x4009B1: main (in /home/arihant/ELF/elf)
当您的一个或多个免费通话无效时,仅仅匹配分配和释放的数量是不够的。您需要使用调试来构建以查看哪个free()是问题。看起来它可能是在read_section_header()中分配的东西或未列出的其他东西。