c - 为什么这个 C 程序会导致段错误(核心转储)?

标签 c arrays pointers memory-management segmentation-fault

我尝试用 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;
}

最佳答案

您没有为list分配足够的内存。只需使其足够大以容纳 num 个数字即可:

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

对于此类问题,valgrind 是您的 friend 。当我运行你的代码时,它说初始化循环正在写入超出分配内存的末尾。

编辑:

这样做还可以节省您预先计算 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;
}

关于c - 为什么这个 C 程序会导致段错误(核心转储)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31349528/

相关文章:

c - `getchar()` 给出与输入字符串相同的输出

c - 传递一维数组、二维数组和指针数组

javascript - 使用循环从父节点中删除元素

c - 为什么这个就地字符串反转函数的第一个字符没有改变?

c - 为什么这段使用 qsort 函数的代码在 C 中不起作用?

ios - 不兼容的指针类型初始化 'NSDate

c++ - `extern "C"`是函数类型的一部分吗?

c++ - C 预处理器字符串化中的额外间接性有所不同

c++用空值初始化二维指针数组?

javascript - 数组中的随机文本字符串