gpt4 book ai didi

c++ - 我在不使用指针的情况下得到 "Segmentation Fault"。怎么了?

转载 作者:太空宇宙 更新时间:2023-11-04 16:14:18 27 4
gpt4 key购买 nike

已解决:段错误是由无限(好吧,不是实际上无限)递归引起的。当我忘记考虑 b = 0 的情况时,无限递归发生在我的 uint pow(uint a, uint b) 函数及其辅助函数中。当b = 0时,b会递减,绕到unsigned int极限,然后不断加栈直到b 回到 1。

感谢@chris 帮助调试,感谢@vsoftco 建议无限递归。


我是 C++ 的新手。我正在编写一个具有 4 个函数的程序,其中 3 个是递归的(我怀疑递归函数与此问题有关)。

基本上,我知道当我到达以下代码行时遇到了段错误:

    uint right = (n % pow(10, i)) / pow(10, i - 1);

此代码位于我的 bool isPalindrome(uint) 函数的 for 循环内。这是我掌握的与段错误有关的唯一信息。

我曾尝试在 stackoverflow 和谷歌上寻找段错误示例,但我找不到任何属于指针之类的东西。

这里出了什么问题?任何和所有帮助将不胜感激。另外,请解释您提出的任何建议,因为我对 C++ 还很陌生,并且打算尽可能多地学习。完整的源代码如下,我认为这对解决这个问题非常有用。

/*
* AUTHORS: Thomas D. Fischer (a.k.a. gragas)
* CREATION DATE: ----:--:-- (YY:MM:DD)
*/

#include <iostream>
#include <time.h>

using namespace std;

typedef unsigned int uint;

bool isPalindrome(uint);
uint length(uint, uint count = 0);
uint pow(uint, uint);
uint powhelper(uint, uint, uint);

int main()
{
clock_t start_time = clock();
cout << "Running program..." << endl;

cout << isPalindrome(12) << endl;

cout << "Execution Time: " << double(clock() - start_time)/CLOCKS_PER_SEC;
}

bool isPalindrome(uint n)
{
for(uint i = 1; i <= length(n)/2; i++)
{
uint left = (n / pow(10, length(n) - i)) % 10;
uint right = (n % pow(10, i)) / pow(10, i - 1);
if( left != right )
return false;
}
return true;
}

uint length(uint n, uint count)
{
if(n != 0)
return length(n /= 10, ++count);
else
return count;
}

uint pow(uint a, uint b)
{
if(b != 1)
return powhelper(a*a, --b, a);
else
return a;
}

uint powhelper(uint a, uint b, uint multiplier)
{
if(b != 1)
return powhelper(a*multiplier, --b, multiplier);
else
return a;
}

最佳答案

您的 pow() 函数无法处理 b=0 的情况。这发生在循环的第一次迭代中(我通过插入几个调试打印输出发现)。

在那种情况下 --b 会溢出并变成一个非常大的数字,这会导致递归溢出堆栈。

段错误来自程序的堆栈溢出。

关于c++ - 我在不使用指针的情况下得到 "Segmentation Fault"。怎么了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24728323/

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