Reputation: 45
EDIT: PROBLEM NOW SOLVED, THANKS ALL
So I'm writing a code for my final piece of C coursework. I've written a function FastDFS which carries out a Fourier Transform. The following code is supposed to time this process for different input sizes.
#include <stdio.h>
#include <stdlib.h>
#include <complex.h>
#include <math.h>
#include <time.h>
void FastDFS(complex double *, complex double *, complex double *, complex double *, int, int);
void print_complex_vector(complex double *, int);
void free_complex_vector(complex double *);
complex double *make_complex_vector(int);
complex double *MakeWpowers(int);
int main(void)
{
int i,N, operations_required;
int index_counter = 1;
double initial_time, final_time, time_taken, mega_flops_rate;
complex double *mega_flops_vector = make_complex_vector(21);
for(N = 2; N <= pow(2,20); N = N * 2)
{
complex double *Wp = MakeWpowers(N);
complex double *y = make_complex_vector(N);
complex double *x = make_complex_vector(N);
complex double *w = make_complex_vector(N);
printf("N = %d\n",N);
operations_required = 1024;
for(i = 1; i <= N; i++)
{
y[i] = i;
}
initial_time = clock();
FastDFS(x,y,w,Wp,N,1);
final_time = clock();
time_taken = (final_time - initial_time) / CLOCKS_PER_SEC;
mega_flops_rate = operations_required / (time_taken * pow(10,6));
free(Wp);
free(y);
free(x);
free(w);
}
return(0);
}
The code has been simplified slightly from the original, but contains the same error. At some stage either the error "timings.out(49621,0x7fff7e684300) malloc: *** error for object 0x7f81ca80c208: incorrect checksum for freed object - object was probably modified after being freed." is returned or Segmentation Fault:11. Where the program crashes varies on different runs, but never gets part N = 8192.
I've written a main function to test the code and don't encounter these errors. The main uses the same functions (make_complex_vector etc). A difference I can see is that I don't free any pointers in the main as I only test it for one value of N at a time, but I don't see how this could cause it to crash? I can run the code for much greater values of N than this in the main.
Can anyone see something obviously wrong here? Many thanks
Upvotes: 2
Views: 117
Reputation: 6745
You are iterating from 1 -> N and assigning to y
. In C, arrays are 0-indexed. For example, if you create an array of size 5, the elements are numbered like so:
[a[0], a[1], a[2], a[3], a[4]]
(5 elements, numbered 0-4)
So instead of
for(i = 1; i <= N; i++)
what you really want is
for(i = 0; i < N; i++)
Otherwise, you are going to write past the end of the allocated memory. If you want the first element of the vector to be 1, write something like this:
for(i = 0; i < N; i++)
{
y[i] = i + 1;
}
(I am assuming that make_complex_vector(N)
allocates an array of size N
).
Upvotes: 1