我在使用简单的类构造函数时遇到了问题。
// 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)
}
模块.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);
}
....
提取器.cpp
#include "Extractor.h"
#include "XModule.h"
#include <iostream>
using namespace std;
int main ()
{
XModule* module = new XModule();
SYSCHAR* fileName = "Greensleeves.xm";
...
return 0;
}
当我使用 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
memset(instr,0,sizeof(TXMInstrument)*256);
行的后面,它将 phead
、instr
和smp<
.
单步执行 gdb 显示 phead
、instr
和 smp<
在此之前设置正确,但数组指针的地址位于为 instr
数组新分配的区域内。检查 &phead
表明这是真的。
为什么新调用 instr = new TXMInstrument[256];
分配用于 phead
、instr
和 smp<
我该怎么做才能解决这个问题或进一步诊断问题?
最佳答案
原来在类定义中有一堆#IFDEF,所以当我针对使用项目 makefile 构建的库编译我的实用程序时,它使用的是源头文件,并认为该类具有不同数量的属性,因此它们在内存中的排列不正确,并被数组的分配压垮了。
我通过不使用项目库、将源文件复制到新文件夹并运行 g++ *.cpp
解决了这个问题。
关于c++ - 在类构造函数的第一行写入大小 8 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10020813/