Reputation: 21
I am writing the code to solve the Rod Cut problem but I have been getting Segmentation Fault prompts at run-time. I tried to debug this using gdb and it showed the issue with the recRodCut function. Can anyone please help me find the issue?
#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);
}
Upvotes: 0
Views: 139
Reputation: 2902
I'm not seeing a segfault here, but I am seeing an unterminated recursion, which ends up in a stack overflow.
Consider how you are calling your recRodCut()
:
recRodCut(value, 4);
// i = 0, first iteration:
res = max(recRodCut(value, 4), value[0]+recRodCut(value, 4-0));
As you can see, you are always calling recRodCut with the same arguments. Which means it will never hit if(n==0)
and bail early.
By the way, your max()
function is actually a min()
function :)
Upvotes: 6