d-team
d-team

Reputation: 3

Memory heap issue C++ , with dynamically allocating multi-dimensional array

I am getting memory heap message from the following C++ script. If I remove the array deallocation, the error goes away. So the bug could be in the deallocation part of the code. I can't able to figure out

if(harmonic_type =='a')
{
    double ** harmonic_content = new double *[number_of_harmonics_required_to_monitor](); 
    for (int i=0;i<number_of_harmonics_required_to_monitor+1;i++) 
    {                                                           
        harmonic_content[i] = new double [2]();                 
    }
    harmonic_content =  harmonic_detector(waveformdata,number_of_samples,samplingrate_Hz, fundamental_frequency_Hz, number_of_harmonics_required_to_monitor,harmonic_type);

    for (int i=1;i<number_of_harmonics_required_to_monitor+1;i++)
    {                                   
        cout<<" Harmonic order "<< i << "::::" << harmonic_content[i][0] << " Hz ::::"<<harmonic_content[i][1] << " :::: "<<harmonic_content[i][2]<<endl;
    }

    for (int i=0;i<number_of_harmonics_required_to_monitor+1;i++) 
    {   
        delete [] harmonic_content [i];                 
    }
    delete [] harmonic_content;
}

Upvotes: 0

Views: 56

Answers (2)

vlad_tepesch
vlad_tepesch

Reputation: 6925

you are using c++. so use its advantages. if number_of_harmonics_required_to_monitor is a compile time constant then your whole code can shrink to:

#include <array>
//...

auto* harmonic_content = new std::array<std::array<double, number_of_harmonics_required_to_monitor>, number_of_harmonics_required_to_monitor>;

for (int i=1;i<number_of_harmonics_required_to_monitor+1;i++)
{                                   
    cout<<" Harmonic order "<< i << " :::: " << (*harmonic_content)[i][0] << "Hz"
                                 << " :::: " << (*harmonic_content)[i][1] 
                                 << " :::: " << (*harmonic_content)[i][2] 
                                 <<endl;
}


delete harmonic_content;

if its not constant you may use sdt::vector.

Even better would be to use some matrix-implementation that keeps track of its own memory.

Upvotes: 0

18446744073709551615
18446744073709551615

Reputation: 16872

In

    new double *[number_of_harmonics_required_to_monitor]()

total elements created: number_of_harmonics_required_to_monitor

In

    for (int i=0;i<number_of_harmonics_required_to_monitor+1;i++)

total elements written: number_of_harmonics_required_to_monitor+1 (from 0 to number_of_harmonics_required_to_monitor)

In

    for (int i=1;i<number_of_harmonics_required_to_monitor+1;i++)

the last read element does not exist: it has has the index number_of_harmonics_required_to_monitor+1

Upvotes: 2

Related Questions