下面我有一段显示非常奇怪行为的代码:
cout<<"Destructing Output "<<(int)output_ptr->keTotalFlag<<endl;
delete output_ptr;
cout<<"Destructed output" <<endl;
以上三行都在另一个名为Simulation的类的析构函数中。 output_ptr是输出类型的指针,是Sim类的公共数据成员。 Output和Sim类之间存在循环依赖关系,因此在代码执行的早期,Simulation将内存分配给指针输出,如下所示:
output_ptr = new Output(this);
我看到的奇怪行为是我能够看到“Destructing Output”cout语句的结果,其中访问了Output类的成员,因此,显然分配给output_ptr的内存尚未被清除。但是,当处理删除语句时,由于双重释放,我得到一个glibc错误。
有人可以告诉我为什么会这样吗?如果您感兴趣,我已经附加了输出类的结构以及来自segfault的堆栈跟踪。
谢谢!
亚洲时报Siddharth
以下是输出类的定义:
class Output {
public:
string outputDir;
vector<double_or_float> keTotal;
vector <int> nPart;
vector<int> pPosWriteIndices; //vector ints store which particles' positions and velocities must be written
vector<int> pVelWriteIndices;
bool particleRFlag; //particle position and velocity write flags
bool particleVFlag;
bool chargeDensityFlag;
bool potentialFlag;
bool eFieldFlag;
bool bFieldFlag;
bool surfChargeFlag;
bool keTotalFlag;
bool nPartFlag;
//text associates output quantity with nsteps and also filenamesuffix.
unordered_map<string,string> fileNameSuffix;
unordered_map<string,int> nStepGridData; //grid data written out every nStepGridData steps
Simulation *sim;
Output(Simulation *sim_input); //constructor
//Some public member functions follow that utilize the data members
}
以下是错误的堆栈跟踪:
*** Error in `bin/pic_testing': double free or corruption (out): 0x0000000000d60110 ***
Destructing Output 1
*** Process received signal ***
Signal: Aborted (6)
Signal code: (-6)
[ 0] /lib/x86_64-linux-gnu/libpthread.so.0(+0x10340) [0x7f0d4a2fa340]
[ 1] /lib/x86_64-linux-gnu/libc.so.6(gsignal+0x39) [0x7f0d49f5bcc9]
[ 2] /lib/x86_64-linux-gnu/libc.so.6(abort+0x148) [0x7f0d49f5f0d8]
[ 3] /lib/x86_64-linux-gnu/libc.so.6(+0x73394) [0x7f0d49f98394]
[ 4] /lib/x86_64-linux-gnu/libc.so.6(+0x7f66e) [0x7f0d49fa466e]
[ 5] bin/pic_testing(_ZN9__gnu_cxx13new_allocatorIiE10deallocateEPim+0x20) [0x4d0046]
[ 6] bin/pic_testing(_ZNSt12_Vector_baseIiSaIiEE13_M_deallocateEPim+0x32) [0x4ccb8a]
[ 7] bin/pic_testing(_ZNSt12_Vector_baseIiSaIiEED2Ev+0x41) [0x4ca32d]
[ 8] bin/pic_testing(_ZNSt6vectorIiSaIiEED2Ev+0x41) [0x4c8705]
[ 9] bin/pic_testing(_ZN6OutputD1Ev+0x5e) [0x4c7be8]
[10] bin/pic_testing(_ZN10SimulationD1Ev+0x10b) [0x4bf00b]
[11] bin/pic_testing(main+0x3b0) [0x4b8ac4]
[12] /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf5) [0x7f0d49f46ec5]
[13] bin/pic_testing() [0x4b83b9]
*** End of error message ***