How to use malloc in a c function?

106 Views Asked by At

I want to make a C function for FIR filter, It has a two input arrays and one output array. both input arrays are constant numbers, I want to use them for computation of output of filter,and after computation delete them and just store the output array of function this is my code but it does not work

#include <stdlib.h>
float   * filter(float *PATIENTSIGNAL,float *FILTERCOEF, int lengthofpatient , int lengthoffilter ){
    static float FIROUT[8000];
    int i,j;
    float temp=0;
    float* SIGNAL;
    float* COEF;
    SIGNAL = malloc(lengthofpatient *sizeof(float));
    COEF = malloc(lengthoffilter*sizeof(float));
    }
    for (j = 0; j <= lengthofpatient; j++){
        temp = SIGNAL[j] * COEF[0];
        for (i = 1; i <= lengthoffilter; i++){
            if ((j - i) >= 0){
                temp += SIGNAL[j - i] * COEF[i];
            }
            FIROUT[j] = temp;
        }
    }
    free(SIGNAL);
    free(COEF);
    free(PATIENTSIGNAL);
    return FIROUT;
}
1

There are 1 best solutions below

0
On

There are several problems in your code,

  1. Unnecessary } after line COEF = malloc(lengthoffilter*sizeof(float));.

  2. for (j = 0; j <= lengthofpatient; j++). This will loop once more than required. The same for the i loop. pmg mentioned it in the comment.

  3. temp += SIGNAL[j - i] * COEF[i]; will not give you the desired outcome, as you do not initialized both SIGNAL or COEF.

  4. Whats the purpose of float *PATIENTSIGNAL,float *FILTERCOEF in the function parameter?

From a wild guess, I think you need this two line to initialize SIGNAL and/or COEF.

memccpy(SIGNAL, PATIENTSIGNAL, lengthofpatient);
memccpy(COEF, FILTERCOEF, lengthoffilter);

Don't free PATIENTSIGNAL in your local function. Let this be done by the function caller.