c - 如何删除此代码中的段错误

标签 c segmentation-fault

我正在编写代码来解决 Rod Cut 问题,但在运行时我一直收到 Segmentation Fault 提示。我尝试使用 gdb 对此进行调试,它显示了 recRodCut 函数的问题。谁能帮我找到问题所在?

#include <stdio.h>

int recRodCut(int* arr, int n)
{
    int res;
    int i;
    if(n==0)
    {
        return 0;
    }

    for( i = 0; i< n ; i++)
    {
        res = max(recRodCut(arr,n) , arr[i]+recRodCut(arr,n-i));
    }

    return res;
}

int max(int a, int b)
{
    return (a<b)?a:b;
}

int main()
{
    int value[] = {0,1,5,8,9,10,17,17,20,24,30};
    int result = recRodCut(value, 4);

    printf("The value is %d \n", result);
}

最佳答案

我在这里没有看到段错误,但我看到了一个未终止的递归,它最终导致堆栈溢出。

考虑如何调用 recRodCut():

recRodCut(value, 4);

// i = 0, first iteration:
    res = max(recRodCut(value, 4), value[0]+recRodCut(value, 4-0));

如您所见,您总是使用相同的参数调用 recRodCut。这意味着它永远不会命中 if(n==0) 并提前退出。


顺便说一句,你的 max() 函数实际上是一个 min() 函数:)

关于c - 如何删除此代码中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31922710/

相关文章:

c - IPv4 地址的 inet_aton 规范化

keyboard - C 中的按键按下和按键释放中断

c - 如何用C语言打印下图?

c - g_slice_alloc 中的段错误

c - 在 C 中 Malloc 字符串数组的数组

c - 高级内存编辑/函数调用

c - strcat 给我一个段错误

c - 读取结构文件时出现段错误

链表段错误的C++数组

c++ - 析构函数不能在 C++ 中为匿名对象工作?