I am writing some code to compute the sum of fibonacci values up to n, as stored in an array. For only certain values of n, I get an error on calling free().
Edit: This code should now compile.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
long fib(long *fibs, int n);
int main(int argc, char *argv[]) {
long num, sum;
long n;
long *fibs;
if(argc < 2) {
printf("Usage %s n\n", argv[0]);
exit(EXIT_SUCCESS);
}
n = strtol(argv[1], NULL, 10);
printf("%ld\n", n);
printf("--Allocating memory\n");
fibs = (long *) malloc(sizeof(long) * n);
printf("--Memory allocated\n");
fibs[0] = 1;
fibs[1] = 1;
sum = 0;
for(int i = 0; i <= n; i++) {
num = fib(fibs, i);
sum += num;
printf("%ld\n", num);
}
printf("%ld\n", sum);
printf("--Freeing memory\n");
free(fibs);
printf("--Memory freed\n");
}
long fib(long *fibs, int n) {
if((n == 0) || (n == 1)) {
return 1;
}
fibs[n] = fibs[n - 1] + fibs[n - 2];
return fibs[n];
}
For instance, when I call the program ./fibsum with n=5, I get a core dump.