0
votes

I'm reading a raw sound file, and I' m trying to run the fft on it, with aim of getting the PSD at the end, but I'm in the start and I get an error that I can't understand, hope getting some help here, the code is:

#include <stdio.h>
#include <fftw3.h>

int main(){
    char* fileName = "sound.raw";
    FILE* inp = NULL;
double* data = NULL;
int index = 0;
fftw_plan  plan;
fftw_complex* out; 
double r,i;
int N = 8192;

//Allocating the memory for the input data 

data = (double*) fftw_malloc(sizeof(double)*N);
out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*N);
plan = fftw_plan_dft_r2c_1d(N,data,out,FFTW_FORWARD);
// opening the file for reading 
inp = fopen(fileName,"rb");
if(inp== NULL){
    printf(" couldn't open the file  \n ");
    return -1;
}
while(!feof(inp)){
    printf( " index  %d",index); // just  get where the program crashs 
        if(index < N){
            fread(&data[index],sizeof(short),1,inp); 
            index = index +1;
        }
        else{
            index = 0;
            fftw_execute(plan);
            printf("New Plan \n");
            printf(" Real \t imag \t Magn \t  \n");
            for(index = 0 ; index<N; index++){
                r=out[index][0];
                i =out[index][1];
                printf("%lf \t %lf \t %lf \t \n",r,i,index);
            }
            index = 0 ;
        }
}
return 0 ; 
}

the program crashes when the index = 8106 and I'm sure that file contain more data. the error that I get is:

Segmentation fault (core dumped )

I know that the error is related to pointer trying to access a memory that it's not allowed to , my question is how can I solve this!

UPDATE

I checked the program again and the error is exactly in line :

fftw_execute(plan) ; 

I hope helps more !

thanks in advance!

1
You seem to be trying to read short data into a buffer of doubles ??? - Paul R
yes is that a problem ?? ? - Engine
I change it to **double ** with no changes - Engine
It's not the cause of your crash, but you must realise that if your file contains 16 bit integer samples then you can't just read this straight into your FFTW input buffer ? - Paul R
Also note that you never check to see whether the FFTW plan creation was successful - my guess is that this is what fails, but since you don't check you don't find out until you crash in fftw_execute with a NULL plan. - Paul R

1 Answers

1
votes

Found it , the error was in the paramter given to the plan function :

plan = fftw_plan_dft_r2c_1d(N,data,out,FFTW_FORWARD); //

should be instead

plan = fftw_plan_dft_r2c_1d(N,data,out,FFTW_MEASURE);

or

plan = fftw_plan_dft_r2c_1d(N,data,out,FFTW_ESTIMATE);

since the direction of the transformation is implicit in the function's name !

thanks anyway !