我尝试在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;
}
答案 0 :(得分:3)
您没有为list
分配足够的内存。只需将其设置为足以容纳num
个数字:
int* list = calloc(num, sizeof(int));
对于这样的问题,valgrind是你的朋友。当我通过它运行代码时,它表示初始化循环正在写入已分配内存的末尾。
编辑:
这样做还可以节省预先计算纤维数量的时间和代码,因此分配前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;
}
答案 1 :(得分:1)
您正试图bytes_to_allocate++
bytes_to_allocate
未初始化。
首先初始化bytes_to_allocate++
。