为什么这个C程序会导致segmentation fault(core dumped)?

Why does this C program lead to a segmentation fault (core dumped)?

我尝试用 C 语言解决数学问题 (https://projecteuler.net/problem=2),但我的程序导致了分段错误。我试过查看代码、在此站点上搜索以及使用 -Wall 和 -Wpedantic 都无济于事。这段代码中到底是什么导致了分段错误(核心已转储)?

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

// Calculates the sum of all fib numbers
// below (non-inclusive) the parameter num.
int calculate(int num) {
    int i = 2, bytes_to_allocate;

    // ---------- BEGIN: Memory Allocation Calculation ----------
    // Calculates the exact number of fibs less than num, and saves this
    // to the variable called "bytes_to_allocate".

    int flist[3]; // A small list of 3 ints to calculate fib numbers.

    flist[0] = 1;
    flist[1] = 2;

    // The if statements in this loop are used to move the
    // index i to the proper place in order to calculate
    // every fib number less than num.
    while(1) {
        if(i == 0) {
            if(flist[i+1] + flist[i+2] >= num) {
                break;
            }
            flist[i] = flist[i+1] + flist[i+2];
            i = 1;
        }
        else if(i == 1) {
            if(flist[i-1] + flist[i+1] >= num) {
                break;
            }
            flist[i] = flist[i-1] + flist[i+1];
            i = 2;
        }
        else if(i == 2) {
            if(flist[i-1] + flist[i-2] >= num) {
                break;
            }
            flist[i] = flist[i-1] + flist[i-2];
            i = 0;
        }
        bytes_to_allocate++;
    }

    // ---------- END: Memory Allocation Calculation ----------

    // Allocates exactly the right amount of bytes corresponding
    // to the number of fibs below value num.
    int* list = calloc(bytes_to_allocate, sizeof(int));

    if(list == NULL) {
        printf("Malloc failed.\n");
        exit(1);
    }

    list[0] = 1;
    list[1] = 2;

    // This loop initializes all fibs that are < num in list.
    for(i = 2; i < num; i++) {
        if(list[i-1] + list[i-2] < num) {
            list[i] = list[i-1] + list[i-2];
        }
        else { // If not less than num
            break;
        }
    }

    // Add all of the even fibs in the list (and the cleared adresses)
    int sum = 0;
    for(i = 0; i < num; i++) {
        if(list[i] % 2 == 0) {
            sum += list[i];
        }
    }

    free(list); // Frees up allocated memory.

    return sum;
}

int main(void) {
    int sum;
    int num = 4000000;
    sum = calculate(num);
    printf("\nSum of even-valued fibs < %d: %d\n\n", num, sum);
    return 0;
}

您正在尝试 bytes_to_allocate++,其中 bytes_to_allocate 未初始化。

先初始化bytes_to_allocate++

您没有为 list 分配足够的内存。让它足够大以容纳 num 个数字:

int* list = calloc(num, sizeof(int));

对于这样的问题,valgrind 是你的朋友。当我 运行 你的代码通过它时,它说初始化循环正在写入已分配内存的末尾。

编辑:

这样做还可以节省您预先计算 fib 数量的时间和代码,因此分配之前 calculate 中的所有内容都可以消失。

编辑 2:

不需要大量内存占用的更简单的方法:

int calculate(int num)
{
    int prev1, prev2, curr;
    int sum;

    sum = 0;
    prev1 = 0;
    prev2 = 1;
    curr = 1;

    while (curr < num) {
        if (curr % 2 == 0) {
            sum += curr;
        }
        prev1 = prev2;
        prev2 = curr;
        curr = prev1 + prev2;
    }
    return sum;
}