如何删除此代码中的分段错误
How to remove the Segmentation Fault in this code
我正在编写代码来解决 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()
函数:)
我正在编写代码来解决 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()
函数:)