簡體   English   中英

為什么此C程序會導致分段錯誤(內核已轉儲)?

[英]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;
}

您沒有為list分配足夠的內存。 只是讓它大到足以容納num數字:

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

對於此類問題,valgrind是您的朋友。 當我在其中運行您的代碼時,它表示初始化循環正在寫入已分配內存的末尾。

編輯:

這樣做還節省了您預先calculate纖維數量的時間和代碼,因此分配之前可以進行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;
}

您正在嘗試bytes_to_allocate++哪里bytes_to_allocate被初始化。

首先初始化bytes_to_allocate++

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM