簡體   English   中英

為什么這個二進制輸出代碼會導致內存泄漏

[英]Why is this binary output code causing a memory leak

我是 C++ 的新手,我正在嘗試輸出一個波形文件。我在 C# 和 Java 中使用二進制文件都取得了成功,但我還不熟悉 C++。 我知道通常應該在堆上創建數組和對象。

字符串和第一個吸氣劑沒問題

每當它到達基類的第二個 getter 時,它就會耗盡內存。 這個類叫做 waveWriter,它擴展了一個叫做 WaveFormat 的類,它包含了 getter

WaveWriter 標題:

class WaveWriter : WaveFormat {
private:
    std::string fileName;

public:
    WaveWriter(uint16_t channels, uint32_t sampleRate,
            uint16_t bitsPerSample, double* lSampleData,
            uint32_t lSampleLength, double* rSampleData,
            uint32_t rSampleLength, bool isFloat, std::string outputName);

    ~WaveWriter();

    void writeWave() {

        std::ofstream myFile;
        myFile = std::ofstream(fileName, std::ios::out | std::ios::binary);

        // write the header
        // sGroupID
        myFile << S_GROUP_ID_HEADER;
        // dwfilelength
        myFile.write(reinterpret_cast<const char *> (GetDwFileLength()),
                sizeof (GetDwFileLength()));
        // sRiffType
        myFile << S_RIFF_TYPE;
        // write the format
        // sGroupID
        myFile << S_GROUP_ID_FORMAT;
        // dwChunkSize
        myFile.write(reinterpret_cast<const char *> (GetDwFormatChunkSize()),
                sizeof (GetDwFormatChunkSize()));
        // wFormatTag
        ........ blah blah blah

        // close file
        myFile.close();

        return;
    }
};

這個類的cpp:

WaveWriter::WaveWriter(uint16_t channels, uint32_t sampleRate,
        uint16_t bitsPerSample, double* lSampleData,
        uint32_t lSampleLength, double* rSampleData,
        uint32_t rSampleLength, bool isFloat, std::string outputName) :
WaveFormat(channels, sampleRate, bitsPerSample,
lSampleData, lSampleLength, rSampleData,
rSampleLength, isFloat) {
    outputName.append(".wav");
    this->fileName = outputName;
}

WaveWriter::~WaveWriter() {
    this->~WaveFormat();
}

WaveFormat 的標頭包含私有變量、構造函數和像這樣訪問私有變量的 getter:

public:
    uint16_t GetCbSize() {
        return cbSize;
    }

    uint32_t GetDwAvgBytesPerSec() {
        return dwAvgBytesPerSec;
    }

    uint32_t GetDwChannelMask() {
        return dwChannelMask;
    }......

這是基於您的函數名稱的推測,但我認為這段代碼:

myFile.write(reinterpret_cast<const char *> (GetDwFileLength()),sizeof (GetDwFileLength()));

是不正確的。 假設GetDwFileLength()返回大小作為值,將其轉換為const char *是不正確的。 您需要將其保存在另一個參數中並發布其地址以進行轉換。 像這樣的東西:

auto val = GetDwFileLength();
myFile.write(reinterpret_cast<const char *> (&val), sizeof (val));

我在您的代碼中多次看到類似的錯誤。 這個錯誤會導致無效的內存訪問。

此外,您應該使用virtual基析構函數,而不是從派生類調用基析構函數。 永遠不要在派生類中調用基析構函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM