'Endless Loop in C while making Fibonacci Sequence with fork()
I am a beginner programmer in C and have been trying to program a Fibonacci sequence sequence in C that reads a command line argument and uses a fork command to output the results. However whenever I run it my program gets stuck in an infinite loop and I have no idea what is causing the issue in the While loop. I haven't been able to use an IDE for this so I apologize for the rough formatting.
int main(int argc, char* argv[])
{
pid_t id;
int x = 0;
int y = 1;
int fib = 0;
long input = 0;
input = (long)argv[1];
id = fork();
if(input < 0){
printf("Enter a positive number. Invalid input");
}
if(id == 0){ /*Child Process */
printf("The numbers in your Fib sequence are: 0, 1, ");
while(input > 0){
fib = x + y;
printf("%d", fib);
x = y;
y = fib;
input = input -1;
}
return 1;
}
else{ /*parent*/
wait(NULL);
printf("Parent is done");
}
return 0;
}
Solution 1:[1]
this is wrong
input = (long)argv[1];
argv[1] is a string. You have forced a pointer into being a long and so have ended up with a huge number.
You need strtol, see https://man7.org/linux/man-pages/man3/strtol.3.html
Test argc first to be sure argc > 1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | pm100 |
