c++ - 在类构造函数的第一行写入大小 8 无效

标签 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)
}

模块.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); 行的后面,它将 pheadinstrsmp<​​.

单步执行 gdb 显示 pheadinstrsmp<​​ 在此之前设置正确,但数组指针的地址位于为 instr 数组新分配的区域内。检查 &phead 表明这是真的。

为什么新调用 instr = new TXMInstrument[256]; 分配用于 pheadinstrsmp<​​ 我该怎么做才能解决这个问题或进一步诊断问题?

最佳答案

原来在类定义中有一堆#IFDEF,所以当我针对使用项目 makefile 构建的库编译我的实用程序时,它使用的是源头文件,并认为该类具有不同数量的属性,因此它们在内存中的排列不正确,并被数组的分配压垮了。

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

关于c++ - 在类构造函数的第一行写入大小 8 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10020813/

相关文章:

c++ - 开始使用 Dev C++ 制作事件驱动的应用程序

C++ RTSP视频采集实现

c++ - 试图解决有关 SECURITY_FLAG_STRENGTH_* 标志的歧义

c - 链表逻辑错误

c++ - 使用 std::sort 对具有结构对的列表进行排序

c++ - 无法在 VS 14 CTP : conditional expression of type 'void' is illegal 中使用 auto 声明 lambda

c - 未初始化的值是由堆栈分配创建的

c++ - 设置返回值时忽略 "still reachable"

c++ - 你如何在 macOS 上使用 Valgrind/Helgrind?

c - Valgrind -> 条件跳转或移动取决于未初始化的值