2012-04-04 49 views
4

我無法讓簡單的類構造函數工作。在類構造函數的第一行寫入大小8無效

// 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) 
} 

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); 

} 
.... 

Extractor.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,instrsmp

使用gdb步進通過透露pheadinstrsmp設置是否正確,在這之前,但數組指針的地址是新的instr陣列分配的區域內。檢查&phead顯示這是事實。

爲什麼一個用於pheadinstrsmp,我能做些什麼來解決這個問題或進一步instr = new TXMInstrument[256];分配內存空間,新的呼叫診斷問題?

+0

雖然你的代碼實際上是不可取的,但在幾乎每一行都很差的C++,它並不是錯誤的。該錯誤必須在其他地方。什麼是1882線? – 2012-04-04 23:47:41

+0

我還會推測,你的類是在無效內存中構建的,可能是一個超過'XModule'對象數組的末尾。這將解釋你的症狀。向我們展示main(Extractor.cpp:9)附近的代碼' – 2012-04-04 23:50:08

+0

寫入大小爲8意味着它是對'phead'的賦值是無效的(即該類本身在無效內存中)。你能提供一個完整的測試用例嗎? – 2012-04-04 23:50:36

回答

4

事實證明,在類定義中有一堆#IFDEFs,所以當我編譯我的實用程序針對使用項目生成文件構建的庫時,它使用源標題並認爲該類具有不同數量的屬性,所以它們沒有被正確地安排在內存中,並被陣列分配所粉碎。

我解決了它通過不使用項目庫,將源文件複製到一個新的文件夾,並運行g++ *.cpp

相關問題