gpt4 book ai didi

c - 为什么这个函数会导致段错误?

转载 作者:行者123 更新时间:2023-12-01 16:19:01 24 4
gpt4 key购买 nike

我编写了以下简单函数来执行模幂运算。但是,当指数参数大于约 261,000 时,它会出现段错误。为什么是这样?我该如何解决?

我在 64 位 Ubuntu 上使用 gcc 进行编译。

谢谢

unsigned int modex(unsigned int base, unsigned int exponent, unsigned int modulus)
{
if(exponent == 1)
return base;

base = base % modulus;

if(exponent == 0 || base == 1)
return 1;

return (modex(base, exponent - 1, modulus) * base) % modulus;
}

最佳答案

@ouah 已经在评论中发布了答案,所以如果他想发布答案,我会删除它。

你有一个堆栈溢出。您递归了太多次并耗尽了堆栈空间。 C++ 不保证尾调用优化(即使你最后没有对递归调用的返回值进行该操作),所以你最好使用循环来实现它。

如果您想坚持递归路线,请尝试通过解释使其成为真正的尾递归 here看看编译器是否能帮助你。

关于c - 为什么这个函数会导致段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15255553/

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