How to remove the Segmentation Fault in this code - c

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);
}

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 :)

Related

Recursive function returns segmentation fault

I want to calculate a number to the power p, got Segmentation fault as a result.
This code is supposed to work:
#include <stdio.h>
int my_power(int nb, int p)
{
if (nb != 0){
return nb*my_power(nb, p-1);
}
return 1;
}
int main(int argc, char argv[]){
printf("%d\n", my_power(5, 3));
return 0;
}
In your code, your recursion never ends.
Change the base case to pb<=0 and it will work.
I have come to a solution by checking for p instead of nb and it worked.
I've added conditions for the negative valeus and the 0^0 case.
int power(int base, int a) {
if ( base=0 && a=0){
return 1;
}
if (a!=0){
return (base * power(base, a-1));
}else{
return 1;
}
}
Thank you for the hints.

I'm learning C programming recursion and doing an activity but I'm stuck

Maybe it's a simple question. I just started learning C alone.
There is a break point
"if" in sumOfDigits function.
But I have no idea why it is a breakpoint...
#include <stdio.h>
int sumOfDigits(int);
int main(int argc, const char * argv[]) {
int N;
scanf("%d", &N);
N = sumOfDigits(N);
printf("%d", N);
return 0;
}
int sumOfDigits (int num)
{
if (num<10)
return num;
else
{
num = sumOfDigits(num)/10;
return num + num%10;
}
}
It shows me like this.
Thread 1: breakpoint 1.1
change
num = sumOfDigits(num)/10;
to
num = sumOfDigits(num/10);
The num variable in your example isn't being decreased, the function will call itself until the memory runs out, and you will have a segmentation fault error.

why are there two outputs for the same c prog below?

#include <stdio.h>
main()
{
int n;
n+=2;
printf("sum=%d", n);
return 0;
}
Here the 'Sum'=2
Another program:-
#include <stdio.h>
main()
{
int n,a=2;
n+=a;
printf("sum=%d", n);
return 0;
}
here the output 'sum' = 3
WHY so?? What is the problem in the code??
This is Undefined Behavior. Using uninitialized variables (n in both snippets) can produce unexpected results, meaning that running the first code twice might produce different outputs. There is no "correct" output for either of the codes, but if you'll set n to a specific value in both codes, you'll start getting consistent results.
This is UB (Undefined Behavior):
main()
{
int n;
printf("sum=%d", n);
return 0;
}
This is not:
main()
{
int n = 0;
printf("sum=%d", n);
return 0;
}
When you don't assign a value to a local variable in C, its value is undefined. So in some cases it will be 0, in some 1, in some, something else entirely. You cannot know what it will be and you should never rely on it. Instead, initialize your local variables:
int n = 0; // initialization
n += 2;
printf("sum=%d", n); // will always print 2

Segmentation Fault in C due to pointer

I have recently started coding in C, and am doing some stuff on project Euler. This is my code for challenge three so far. The only problem is when I run the compiled code it throws a segmentation fault. I think it may be due to a pointer I called, the suspect pointer is underneath my comment. I did some research into the subject but I cant seem to be able to fix the error. Any advice?
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
bool is_prime(int k);
int * factors(int num);
int main(){
int input;
while (true){
printf("Enter a number to get the prime factorization of: ");
scanf("%d", &input);
if (is_prime(input) == true){
printf("That number is already prime!");
}else{
break;
}
}
//This is the pointer I think is causing the problem
int * var = factors(input);
int k;
for (k = 0; k < 12; k++){
printf("%d", var[k]);
}
}
bool is_prime(int k){
int i;
double half = ceil(k / 2);
for (i = 2; i <= half; i++){
if (((int)(k) % i) == 0){
return false;
break;
}
}
return true;
}
int * factors(int num){
int xi;
static int array[1000];
int increment = 0;
for (xi = 1;xi < ceil(num / 2); xi++){
if (num % xi == 0){
array[increment] = xi;
increment++;
}
}
}
The factors function has no return statement. It's supposed to return a pointer but it doesn't return anything.
Side note: Enable your compiler's warnings (e.g., with gcc -Wall -Wextra). If they're already enabled don't ignore them!
Your function is declared as
int * factors(int num);
but it's definition doesn't return anything and yet you are using it's return value in assignment. This triggers undefined behavior. It will compile if compiled without rigorous warnings and the return value will most likely be whatever random value happened to be left in the return register (e.g. EAX on x86).
C-99 Standard ยง 6.9.1/12 Function definitions
If the } that terminates a function is reached, and the value of the
function call is used by the caller, the behavior is undefined.

segmentation fault during execution of program

I have written a program to create 10 threads and run them normally. The Program is running fine but at the end it gives a segmentation fault. What is this fault, what is causing it, and how do I resolve it?
My code is :
#include<stdio.h>
#include<pthread.h>
void *print(void *num);
int main()
{
pthread_t tid[10];
int n,check;
void *exitstatus;
for(n=1;n<=10;n++)
{
check=pthread_create(&tid[n],NULL,print,(void *)&n);
if(check=0)
printf("thread created");
pthread_join(tid[n],&exitstatus);
}
return 0;
}
void *print(void *num)
{
int i,*val=(int *)num;
for(i=0;i<(5);i++)
printf("Hello World!!!(thread %d )\n",*val);
}
You have many flaws:
for(n=1;n<=10;n++) // No, The array starts from 0 and lasts on 9
Try this
for(n=0;n<10;n++)
if(check=0) // No, this will assign 0 to check instead of compare it
Try this
if(check==0)
You are accessing an array beyond its index. It is undefined behavior.
your array t[10] starts at index t[0] and should end at t[9] -
for(n = 0; n < 10; n++) {
//your stuff
}
Also check == 0 is how you check equality. check = 0 will assign 0 to check
So your code must look like this:
#include<stdio.h>
#include<pthread.h>
void *print(void *num);
int main()
{
pthread_t tid[10];
int n,check;
void *exitstatus;
for(n = 0; n < 10; n++)
{
check=pthread_create(&tid[n], NULL, print, (void *)&n);
if(check == 0)
printf("thread created");
pthread_join(tid[n], &exitstatus);
}
return 0;
}
void *print(void *num)
{
int i,*val=(int *)num;
for(i = 0; i < 5; i++)
printf("Hello World!!!(thread %d )\n", *val);
}
Another important note on programming style: Please use proper indentation and use whitespace judiciously. Most programming errors and bugs can be eliminated if proper indentation and whitespace is used. For example, one white space before and after an operator in the for loop, and between parameters while calling a function after , and before the next parameter.

Resources