red*_*888 0 c valgrind memory-leaks buffer-overflow
我正在学习C并经历一个包含valgrind使用的教程.我还在了解valgrind实际上在做什么,并想知道是否有人可以解释为什么它没有检测到以下代码中的任何错误:
#include <stdio.h>
int main(int argc, char *argv[])
{
int numbers[4] = {0,1,2,3,4};
// first, print them out raw
printf("numbers: %d %d %d %d %d\n",
numbers[0], numbers[1],
numbers[2], numbers[3],
numbers[4]);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我确实遇到编译器错误:
greggery@Lubu:~/code$ make lc
cc -Wall -g lc.c -o lc
lc.c: In function ‘main’:
lc.c:5:2: warning: excess elements in array initializer [enabled by default]
lc.c:5:2: warning: (near initialization for ‘numbers’) [enabled by default]
Run Code Online (Sandbox Code Playgroud)
但是当我对着valgrind运行时,它没有看到任何错误:
==2300== Memcheck, a memory error detector
==2300== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==2300== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==2300== Command: ./lc
==2300==
numbers: 0 1 2 3 69156864
==2300==
==2300== HEAP SUMMARY:
==2300== in use at exit: 0 bytes in 0 blocks
==2300== total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==2300==
==2300== All heap blocks were freed -- no leaks are possible
==2300==
==2300== For counts of detected and suppressed errors, rerun with: -v
==2300== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
Run Code Online (Sandbox Code Playgroud)
这里没有内存问题,因为我在数组中添加了一个额外的元素?我认为valgrind会发现最后一个元素有问题,因为它在数组之外.
您array的存储stack area和Valgrind检查区域中的泄漏.heap它检查分配的内存泄漏,dynamic allocation因此您没有得到任何检测Valgrind.
如果你真的想看到效果,那么使用下面的代码
int main()
{
int *p=malloc(6);
}
Run Code Online (Sandbox Code Playgroud)
并用于Valgrind检查内存泄漏.
| 归档时间: |
|
| 查看次数: |
546 次 |
| 最近记录: |