在类构造函数的第一行中无效写入8号

Dan*_*ore 6 c++ valgrind

我在让一个简单的类构造函数工作时遇到麻烦。

// In XModule.h
class XModule
{
...
public:
  TXMHeader     header;     // module header
  TXMInstrument*    instr;      // all instruments (256 of them)
  TXMSample*        smp;        // all samples (256 of them, only 255 can be used)
  TXMPattern*       phead;      // all pattern headers (256 of them)
}
Run Code Online (Sandbox Code Playgroud)

Module.cpp

// In XModule.cpp
....
XModule::XModule()
{
  // allocated necessary space for all possible patterns, instruments and samples
  phead = new TXMPattern[256]; // Line # 1882
  instr = new TXMInstrument[256];
  smp = new TXMSample[MP_MAXSAMPLES];

  memset(&header,0,sizeof(TXMHeader));

  if (instr)
    memset(instr,0,sizeof(TXMInstrument)*256);

  if (smp)
    memset(smp,0,sizeof(TXMSample)*MP_MAXSAMPLES);

  if (phead)
    memset(phead,0,sizeof(TXMPattern)*256);

}
....
Run Code Online (Sandbox Code Playgroud)

提取器

#include "Extractor.h"
#include "XModule.h"

#include <iostream>
using namespace std;

int main ()
{
  XModule* module = new XModule();
  SYSCHAR* fileName = "Greensleeves.xm";

  ...

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我使用valgrind运行时,出现以下错误:

==21606== Invalid write of size 8
==21606==    at 0x408BD3: XModule::XModule() (XModule.cpp:1882)
==21606==    by 0x4012D8: main (Extractor.cpp:9)
==21606==  Address 0x64874f0 is not stack'd, malloc'd or (recently) free'd
Run Code Online (Sandbox Code Playgroud)

该行的memset(instr,0,sizeof(TXMInstrument)*256);末尾归零pheadinstrsmp

通过使用gdb步进透露pheadinstrsmp设置是否正确,在这之前,但数组指针的地址是新的分配区域内的instr阵列。检查&phead发现这是真的。

为什么新调用instr = new TXMInstrument[256];一个用于分配的内存空间pheadinstr并且smp,我能做些什么来解决这个问题或进一步诊断问题?

Dan*_*ore 6

事实证明,类定义中有一堆#IFDEF,因此,当我针对使用项目makefile构建的库编译实用程序时,它使用的是源标头,并认为该类具有不同数量的属性,因此它们是没有正确地安排在内存中,并被数组分配压碎了。

我通过不使用项目库,将源文件复制到新文件夹并运行来解决了该问题g++ *.cpp