我从以下C ++脚本获取内存堆消息。如果我删除数组释放,则错误消失。所以bug可能在代码的deallocation部分。我无法弄清楚
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;
}
答案 0 :(得分:2)
在
new double *[number_of_harmonics_required_to_monitor]()
创建的总元素:number_of_harmonics_required_to_monitor
在
for (int i=0;i<number_of_harmonics_required_to_monitor+1;i++)
写入的总元素:number_of_harmonics_required_to_monitor+1
(从0到number_of_harmonics_required_to_monitor
)
在
for (int i=1;i<number_of_harmonics_required_to_monitor+1;i++)
最后一个读取元素不存在:它具有索引number_of_harmonics_required_to_monitor+1
答案 1 :(得分:0)
你正在使用c ++。所以利用它的优势。
如果number_of_harmonics_required_to_monitor
是编译时常量,则整个代码可缩小为:
#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;
如果它不是常数,你可以使用sdt :: vector。
更好的方法是使用一些跟踪自己内存的矩阵实现。