简体   繁体   中英

Why do I get the error “Segmentation fault (core dumped)”?

I just started with C programming and I'm making a program that calculates a specific amount of Fibonacci numbers. It works fine, except that I get the error "Segmentation fault (core dumped)". What's wrong with my code?

#include <stdio.h>

int main() {
    int max;
    long long int fiNum[] = {1, 1};

    printf("How many numbers do you want to get? ");
    scanf("%d", &max);

    int i = 1;
    long long int x;

    while ( i < max ) {
        x = fiNum[i] + fiNum[i-1];
        printf("%lld ", x);
        i++;
        fiNum[i] = x;
    }

    printf("\nDone!\n");
    return 0;
}

When I ask for let's say 10 numbers the output is:

2 3 5 8 13 21 34 55 89 
Done!
Segmentation fault (core dumped)

I'm using Linux (Ubuntu) btw.

Thanks in advance.

You're going out-of-bound accessing the static array fileNum for which only 2 elements are allocated.

Hence you're the victim of undefined behavior. Anything could happen but in your case it's crashing at the end.

If you want to store the generated fibonacci numbers then better dynamically allocate the array after getting the input from the user.

since you said that you are a C beginner, here are some tips :) :

#include <stdio.h>

int main () {

    /*When you program in C, try to declare all your variables at the begining of the  code*/
    int max;
    long long int fiNum[]={1,1}; /* malloc! It is allways the solution and the problem too, but stick with malloc
                something like fiNum = malloc (n*sizeof(long int)); I never malloc a long int
                so just verify if its like this...
                   */
    long long int x;
    int i=1; /*Try to only initializes loop variables inside the loop, like: for(i=1; i< max; i++){}*/

    printf("How many numbers do you want to get? ");
    scanf("%d",&max);

    printf("max: %d\n", max);

    while (i<max) { /*Here you could use a for loop*/
        printf("i value: %d\n",i);
        x=fiNum[i]+fiNum[i-1];
        printf("%lld ",x);
        i++;
        fiNum[i]=x;
    }

printf("\nDone!\n");
return 0;
}

Obs.: I had run your code in my linux and because invalid access to vector position it didn't print all the numbers that I asked.

And now, the fixed code:

#include <stdio.h>
#include <stdlib.h>

int main () {

    int max;
    int i;
    long long int *fiNum;

    printf("How many numbers do you want to get? ");
    scanf("%d",&max);

    fiNum = malloc(max*sizeof(long int));
    fiNum[0] = 1;
    fiNum[1] = 1;

    for (i = 1; i < max-1; i++) 
      fiNum[i+1] = fiNum[i]+fiNum[i-1];

    for (i = 0; i < max; i++) 
      printf("fi[%d]: %d\n", i+1, fiNum[i]);

    printf ("\nDone!\n");
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM