c - 为什么我的按位除法函数会产生段错误?

标签 c segmentation-fault bit-manipulation

我的代码如下,它适用于大多数输入,但我注意到,对于非常大的数字(对于特定示例,2147483647 除以 2),我会遇到段错误,并且程序停止工作。请注意,badd() 和 bsub() 函数分别简单地添加或减去整数。

unsigned int bdiv(unsigned int dividend, unsigned int divisor){  
    int quotient = 1; 
    if (divisor == dividend)
    {
        return 1; 
    }
    else if (dividend < divisor)
    {   return -1; }// this represents dividing by zero

    quotient = badd(quotient, bdiv(bsub(dividend, divisor), divisor));

    return quotient;
}

我的 bmult() 函数也遇到了一些问题。它适用于某些值,但对于 -8192 乘以 3 等值,程序会失败。还列出了此函数。预先感谢您的任何帮助。我真的很感激!

int bmult(int x,int y){
    int total=0;
    /*for (i = 31; i >= 0; i--)
    {
        total = total << 1;
        if(y&1 ==1)
        total = badd(total,x);
    }
    return total;*/ 
    while (x != 0)
    {
        if ((x&1) != 0)
        {
            total = badd(total, y);
        }
        y <<= 1;
        x >>= 1;
    }
    return total; 
}

最佳答案

bdiv 的问题很可能是由递归深度引起的。在您给出的示例中,您将把大约 1073741824 个帧放入堆栈中,基本上耗尽了分配的内存。

事实上,这个函数没有真正的理由需要递归。我可以很容易地转换为迭代解决方案,从而缓解堆栈问题。

关于c - 为什么我的按位除法函数会产生段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12720182/

相关文章:

C - 需要比较 int 的最低位 `n` 是否相等

c - 就地按位 AND 然后恢复原始值

c - Linux | C 中的 Shell 实现 |重定向文件包括提示

c - 找到矩阵中等于坐标 (i+j) 之和的所有元素

c - 内存不足..怎么办?

当数据复制/扫描/读取到未初始化的指针时崩溃或 "segmentation fault"

c - C:将主要功能移至新文件时出现段错误

c - 这个 k&r 第 2 章的例子错了吗?

c - 保持前导零 C

c - 为给定掩码生成所有位模式