我有一个C程序员(有很多数字,而且太长了,不能发表),我用它编译
gcc -g -O0 program.c -o program我正在尝试使用gdb和valgrind memcheck对其进行调试。在对代码进行了一些更改之后,我发现
valgrind --tool=memcheck --log-file=output.log ./program给出
==15866== Memcheck, a memory error detector
==15866== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==15866== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==15866== Command: ./program
==15866== Parent PID: 3362
==15866==
==15866== Warning: client switching stacks? SP change: 0xbe88bcd8 --> 0xbe4e1f70
==15866== to suppress, use: --max-stackframe=3841384 or greater
==15866== Invalid write of size 4
==15866== at 0x804B7BE: main (program.c:1396)
==15866== Address 0xbe4e1f74 is on thread 1's stack
==15866==
==15866== Invalid write of size 4
==15866== at 0x804B7C2: main (program.c:1396)
==15866== Address 0xbe4e1f70 is on thread 1's stack
==15866==
==15866== Invalid read of size 4
==15866== at 0x4320011: on_exit (on_exit.c:34)
==15866== by 0x43064D2: (below main) (libc-start.c:226)
==15866== Address 0xbe4e1f70 is on thread 1's stack
==15866==
==15866== Invalid read of size 4
==15866== at 0x4320022: on_exit (on_exit.c:37)
==15866== by 0x43064D2: (below main) (libc-start.c:226)
==15866== Address 0xbe4e1f74 is on thread 1's stack还有更多这类的。
valgrind --tool=memcheck --max-stackframe=3841384 --log-file=output.log ./program不打印任何错误。但令我困惑的是,对于这两个valgrind调用,程序都提前退出(没有错误消息),并且没有执行它应该执行的计算。使用相同的编译器选项但不使用valgrind运行的行为是完全不同的,看起来非常正常。但是,我怀疑是内存错误,并希望使用valgrind来找到它。因此,我的问题是:当使用valgrind执行程序时,什么样的错误会使程序表现得如此不同?如果这些是与内存相关的错误,我如何识别它?请注意,我很清楚,我可以“手动调试”来定位它。但是,我可以使用valgrind运行gdb来查看它的出口吗?
发布于 2012-09-27 23:19:48
我最初在评论中回答:
您可能会导致堆栈溢出。你在堆栈上分配“大”数组吗?例如,
double myArray[10000000];,如果是这样,那么您应该使用malloc和free将这种分配替换为堆内存。
我写了一个简短的c程序,故意造成像这样的堆栈溢出,并检查valgrind报告的内容:
#include <stdio.h>
int main(){
// imax*sizeof(double) is too big for the stack.
int imax = 10000000;
double test[imax];
// I do a little math to prevent the stack overflow from being optimized away if -O3 is used.
test[0]=0;
test[1]=1;
for(int i=2; i<imax; i++)
test[i]=0.5*(test[i-1]+test[i-2]);
printf("%e\n", test[imax-1]);
}果然,valgrind想出了:
==83869== Warning: client switching stacks? SP change: 0x104802930 --> 0xffbb7520
==83869== to suppress, use: --max-stackframe=80000016 or greater
==83869== Invalid write of size 8
==83869== at 0x100000ED0: main (in ./a.out)
==83869== Address 0xffbb7520 is on thread 1's stack以及大量其他错误消息,并最终退出并返回Segmentation fault: 11
https://stackoverflow.com/questions/12624373
复制相似问题