Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Execution Error

NavicNavic Member Posts: 109
I'm using gcc on linux and this source code compiles fine, but upon execution I get "Segmentation fault (core dumped)" after entering the input. What am I doing wrong?

[code]#include "stdio.h"
main()
{
int input;
printf("How Many?: ");
scanf ("%d", &input);
printf("%d
", fibonacci(input));
}

int fibonacci(unsigned int n)
{
unsigned int result;
if (n == 1)
result = 0;
if (n == 2)
result = 1;
result = fibonacci(n - 1) + fibonacci(n - 2);
return result;
}[/code]

Comments

  • zibadianzibadian Member Posts: 6,349
    : I'm using gcc on linux and this source code compiles fine, but upon
    : execution I get "Segmentation fault (core dumped)" after entering
    : the input. What am I doing wrong?
    :
    : [code]: #include "stdio.h"
    : main()
    : {
    : int input;
    : printf("How Many?: ");
    : scanf ("%d", &input);
    : printf("%d
    ", fibonacci(input));
    : }
    :
    : int fibonacci(unsigned int n)
    : {
    : unsigned int result;
    : if (n == 1)
    : result = 0;
    : if (n == 2)
    : result = 1;
    : [red]result = fibonacci(n - 1) + fibonacci(n - 2);[/red]
    : return result;
    : }[/code]:
    The red line runs always, even if n < 2. This will eventually result in an overflow on the minimum size of the integer, or in a stack overflow.
  • freelance starfreelance star Member Posts: 73
    : I'm using gcc on linux and this source code compiles fine, but upon
    : execution I get "Segmentation fault (core dumped)" after entering
    : the input. What am I doing wrong?
    :
    : [code]: #include "stdio.h"
    : main()
    : {
    : int input;
    : printf("How Many?: ");
    : scanf ("%d", &input);
    : printf("%d
    ", fibonacci(input));
    : }
    :
    : int fibonacci(unsigned int n)
    : {
    : unsigned int result;
    : if (n == 1)
    : result = 0;
    : if (n == 2)
    : result = 1;
    : result = fibonacci(n - 1) + fibonacci(n - 2);
    : return result;
    : }[/code]:
    [code]
    if(n<=2)
    return 1;
    [/code]
    [B][link=http://expert.myitcareer.org/]Freelance Programmer[/link]|[link=http://myitcareer.org/]Interview Question And Answer[/link][/B]
Sign In or Register to comment.