4

我知道 Valgrind 以允许捕获段错误的方式跟踪内存。但是,为什么没有捕捉到以下段错误?

int main() {
    char *x = calloc(16, 1);
    char *y = calloc(16, 1);

    x[80] = 'c';
    y[-80] = 'c';

    printf("%c %c\n", *x, *y);
    return 0;
}

它不应该捕获堆中的越界访问吗?根据 Valgrind 的文档:

But it should detect many errors that could crash your program (eg. cause a segmentation fault).
4

2 回答 2

6

我认为你赋予 valgrind 权力而不是可能的权力。

它会尝试检测各种类型的错误并将它们报告给您,但它不可能检测到所有错误,即使在它尝试检测的某些错误类别中也是如此。

在这种情况下,您正在处理的是对数组的越界写入,如果 valgrind 设法捕获它,将被报告为“无效写入”错误。这些是通过跟踪哪些地址是“有效的”来检测的,因为它们是已知堆块的一部分。

问题是,如果你索引太远超出数组的开头或结尾,你实际上可能会得到一个在相邻块中是有效地址的地址,因此对于 valgrind 来说看起来绝对没问题。为了减少这种情况发生的可能性,valgrind 在块的每一侧添加了一个填充区域(称为“红色区域”),但默认情况下只有 16 个字节。

如果您使用该--redzone-size=128选项增加红色区域的大小,那么您会发现 valgrind 确实检测到该程序中的错误。

于 2012-10-31T21:23:37.243 回答
1

为我工作:

==24344== Memcheck, a memory error detector.
==24344== Copyright (C) 2002-2007, and GNU GPL'd, by Julian Seward et al.
==24344== Using LibVEX rev 1854, a library for dynamic binary translation.
==24344== Copyright (C) 2004-2007, and GNU GPL'd, by OpenWorks LLP.
==24344== Using valgrind-3.3.1-Debian, a dynamic binary instrumentation framework.
==24344== Copyright (C) 2000-2007, and GNU GPL'd, by Julian Seward et al.
==24344== For more details, rerun with: -v
==24344== 
==24344== Invalid write of size 1
==24344==    at 0x8048419: main (testValgrind.c:5)
==24344==  Address 0x418f078 is 0 bytes after a block of size 16 alloc'd
==24344==    at 0x4021E22: calloc (vg_replace_malloc.c:397)
==24344==    by 0x804840F: main (testValgrind.c:3)
==24344== 
==24344== Invalid write of size 1
==24344==    at 0x8048422: main (testValgrind.c:6)
==24344==  Address 0x418f018 is 16 bytes before a block of size 16 alloc'd
==24344==    at 0x4021E22: calloc (vg_replace_malloc.c:397)
==24344==    by 0x80483F8: main (testValgrind.c:2)

==24344== 
==24344== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 12 from 1)
==24344== malloc/free: in use at exit: 32 bytes in 2 blocks.
==24344== malloc/free: 2 allocs, 0 frees, 32 bytes allocated.
==24344== For counts of detected errors, rerun with: -v
==24344== searching for pointers to 2 not-freed blocks.
==24344== checked 58,940 bytes.
==24344== 
==24344== LEAK SUMMARY:
==24344==    definitely lost: 32 bytes in 2 blocks.
==24344==      possibly lost: 0 bytes in 0 blocks.
==24344==    still reachable: 0 bytes in 0 blocks.
==24344==         suppressed: 0 bytes in 0 blocks.
==24344== Rerun with --leak-check=full to see details of leaked memory.
于 2012-10-31T21:20:50.153 回答