简体   繁体   English

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

[英]Why does this function cause a segfault?

I wrote the following simple function to perform modular exponentiation. 我编写了以下简单函数来执行模幂运算。 However, it segfaults when the exponent parameter is greater than about 261,000. 但是,当指数参数大于约261,000时,它会发生段错误。 Why is this? 为什么是这样? And how can I fix it? 我该如何解决?

I'm compiling with gcc on 64-bit Ubuntu. 我正在使用64位Ubuntu上的gcc进行编译。

Thanks 谢谢

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 already posted the answer in a comment, so if he wants to post an answer I'll delete this. @ouah已经在评论中发布了答案,所以如果他想发一个答案,我会删除它。

You have a stack overflow. 你有一个堆栈溢出。 You are recursing too many times and blowing your stack space. 您正在递归太多次并且会浪费您的堆栈空间。 C++ does not guarantee tail call optimization (even if you didn't have that operation on the return value of the recursive call at the end), so you're better off implementing this using a loop. C ++不保证尾部调用优化(即使你最后没有对递归调用的返回值进行该操作),所以最好使用循环实现它。

If you want to stick with the recursive route, try making it truly tail recursive via the explanation here and see if the compiler helps you out. 如果你想坚持递归路由,请尝试通过这里的解释使其真正的尾递归,看看编译器是否帮助你。

You're creating a enormous recursion chain. 你正在创建一个巨大的递归链。 You should try to save memory and processing by doing it iterative. 你应该尝试通过迭代来节省内存和处理。

unsigned modex(unsigned base, unsigned exponent, unsigned modulus){

    unsigned
        result = 1;

    while(expoent--){
        result *= base;
        result %= modulus;

    }

    return result;

}

Still, you can do it even faster. 不过,你可以做得更快。

Your recursion becomes so deep that it takes up the entire sack. 你的递归变得如此之深以至于占据了整个麻袋。 Consider using a while loop instead. 请考虑使用while循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM