gpt4 book ai didi

c - 程序通过 valgrind memcheck 提前终止

转载 作者:太空狗 更新时间:2023-10-29 17:25:14 26 4
gpt4 key购买 nike

我有一个 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 以查看它退出的位置。

最佳答案

我最初在评论中回答:

You're probably causing a stack overflow. Are you allocating "large" arrays on the stack? E.g. double myArray[10000000]; If so then you should replace such allocations with heap memory using malloc and 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

退出

关于c - 程序通过 valgrind memcheck 提前终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12624373/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com