gpt4 book ai didi

c++ - 使用 GDB 调试时段错误消失

转载 作者:太空狗 更新时间:2023-10-29 21:22:29 24 4
gpt4 key购买 nike

运行此代码 时出现段错误:http://ideone.com/yU80Bd

问题是当我在 GDB 中运行它时,代码运行良好且出色。为什么它在没有段错误的 gdb 中运行,但在其他地方运行却出现段错误?

这是我要解决的问题:http://www.codechef.com/DEC13/problems/CHODE

最佳答案

问题是您输入的字符不在 [a-Z] 范围内。例如:! 这会导致在无效索引处访问 vector 。

您可以使用 valgrind 检查运行您的程序的这些内容。

valgrind ./ideone < stdin
...
==2830== Invalid read of size 4
==2830== at 0x40111A: main (ideone.cpp:53)
...
==2830== Invalid write of size 4
==2830== at 0x401120: main (ideone.cpp:53)

问题出在这几行:

    for(int i=0;i<cipherText.size();++i)
{
char c = tolower(cipherText[i]);
++(cipherF[c-97].frequency);
}

c - 97 可能小于 0。

你可以检查,例如:

    for(int i=0;i<cipherText.size();++i)
{
char c = tolower(cipherText[i]);
if (c < 'a' || c > 'z') continue;
++(cipherF[c-97].frequency);
}

关于c++ - 使用 GDB 调试时段错误消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20496145/

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