I wrote Cooley-Tukey's FFT algorithm in C. And I want to know how safe is this code? Is it just trash? How can I make it more memory safe?
#include <stdio.h>
#include <complex.h>
#include <stdlib.h>
#include <math.h>
#define PI 3.14159265358979323846
void fft(double complex *x, unsigned int N, double complex *result){
if(N == 1){
result[0] = x[0];
return;
}
double complex sub_even[N/2];
double complex sub_odd[N/2];
for(unsigned int i = 0; i < N/2; i++){
sub_even[i] = x[2 * i];
sub_odd[i] = x[2 * i + 1];
}
double complex *even = (double complex *)malloc(sizeof(double complex) * (N/2));
double complex *odd = (double complex *)malloc(sizeof(double complex) * (N/2));
fft(sub_even, N/2, even);
fft(sub_odd, N/2, odd);
for(unsigned int k = 0; k < N / 2; k++){
double complex twiddle = cexp(-2 * I * PI * k / N) * odd[k];
result[k] = even[k] + twiddle;
result[k + N/2] = even[k] - twiddle;
}
free(even);
free(odd);
}
int main(){
unsigned int N = 8;
double complex x[N];
for(unsigned int i = 0; i < N; i++){
x[i] = i+1;
}
double complex *result = (double complex *)malloc(sizeof(double complex) * N);
fft(x, N, result);
for(unsigned int i = 0; i < N; i++){
printf("%.2f + %.8fj\n", creal(result[i]), cimag(result[i]));
}
return 0;
}