I am dealing with a problem, that has to do with dynamic allocation, in c++. I have the following function to calculate the rms of a signal
void FindRMS(int points, double* signal_x, double* signal_y, int presamples, double* mean, double* rms)
{
//double fraction_presamples_RMS = 0.9; // fraction of presamples to calculate RMS
//Safety condition
if (presamples>points) {
printf("\nERROR: Too many presamples!\n\n");
return;
}
//Main procedure
(*rms) =0.;
(*mean) =0.;
for (int i=0; i<presamples; i++) {
(*mean)+=signal_y[i];
(*rms)+=pow(signal_y[i],2);
}
(*mean)/=presamples;
(*rms)=sqrt((*rms)/presamples-pow((*mean),2));
cout << "RMS was found to be : " << (*rms) << endl;
}
First of all, if I understand correctly, double* <var>
means that the argument is expected to be dynamically defined, which means that its size will be limited by the hardware.
Then what I do, is to call this function in my code. A sample code is the following
void Analyze(unsigned int first_run, unsigned int last_run, unsigned int last-segment){
int points = 9e6;//hSignal->GetNbinsX();
//double x[points], y[points], derivative[points]; // SIZE limited by COMPILER to the size of the stack frame
double* x = new double[points]; // SIZE limited only by OS/Hardware
double* y = new double[points];
double* derivative = new double[points];
double* mean = new double[points];
double* rms = new double[points];
for (int i = 0; i < points; i++){
x[i] = hSignal->GetBinLowEdge(i+1);
y[i] = hSignal->GetBinContent(i+1);
//cout << " Bin Center " << hSignal->GetBinLowEdge(2) << endl;
}
FindRMS(points, x, y, 0.9*points, mean, rms);
delete[] x;
delete[] y;
delete[] mean;
cout << "The value of rms[10] = " << rms[10] << endl;
}
The weird thing is that when the program is executed I get a cout from the function with a logical rms, while before the program end I get that rms is 0.
Any idea or advice on why this is happening? The thing is that I have to stick with the function as is, because it belongs to a library I have to stick with...
I thought of changing the function to return a double*
instead of void
but nothing changed really... Here is the modified function
double* FindRMS(int points, double* signal_x, double* signal_y, int presamples, double* mean, double* rms)
{
//double fraction_presamples_RMS = 0.9; // fraction of presamples to calculate RMS
//Safety condition
if (presamples>points) {
printf("\nERROR: Too many presamples!\n\n");
//return;
}
//Main procedure
(*rms) =0.;
(*mean) =0.;
for (int i=0; i<presamples; i++) {
(*mean)+=signal_y[i];
(*rms)+=pow(signal_y[i],2);
}
(*mean)/=presamples;
(*rms)=sqrt((*rms)/presamples-pow((*mean),2));
cout << "RMS was found to be : " << (*rms) << endl;
return rms;
}