2017-02-27 37 views
0

我得到這個錯誤(內存位置不同運行): 釋放內存! Image_Processing(6282,0x100091000)的malloc:*錯誤對象0x1212121212121212:被釋放的指針沒有被分配 *設置malloc_error_break斷點在這一點上它崩潰調試C++不正確的校驗和爲釋放的對象-

://刪除M_DATA;

class Uint8Image { 
public: 
    uint32_t m_w; 
    uint32_t m_h; 
    uint8_t *m_data; 


    Uint8Image(uint32_t w, uint32_t h): m_w(w), m_h(h), m_data(0) 
    { 
     m_data = new uint8_t(w*h); 
    } 

    Uint8Image(const Uint8Image &obj) ; 

    Uint8Image& operator = (const Uint8Image &D) { 
     if(this != &D) 
     { 
      delete [] m_data; 
      m_w= D.m_w; 
      m_h = D.m_h; 
      m_data=new uint8_t(m_w * m_h); // deep copy the pointer data 
     } 
     return *this; 
    } 

~Uint8Image() 
    { 
     std::cout << "Freeing memory!"<< std::endl; 
    delete m_data; // it crashes here 
    m_data = NULL; 
    } 

}; 

class MeniscusFinderContext { 

public: 

    MeniscusFinderContext(uint32_t m_a, uint32_t m_b): 

    { 
     m_input_image = new Uint8Image(m_a,m_b); 

    } 

    ~MeniscusFinderContext() 
    { 
     delete m_input_image; 
     m_input_image = NULL; 

    } 

Uint8Image m_input_image;}; 

//The function that calls: 

//以通過選項的解析輸入,

int main(int argc, char *argv[]{ 
const char *file_name = options[INPUT].arg; 

    std::ifstream file_stream(file_name, 
           std::ifstream::in | std::ifstream::binary); 
    char buf[256]; 
    char *sEnd; 
    file_stream.getline(buf, sizeof(buf)); 
    if(buf[0] != 'P' || buf[1] != '5') { 
     std::cerr << "invalid input PGM file" << std::endl; 
     return 1; 
    } 
    file_stream.getline(buf, sizeof(buf)); 
    while(buf[0] == '#') file_stream.getline(buf, sizeof(buf)); 
    uint32_t m_a = strtol(buf, &sEnd, 10); 
    uint32_t m_b = strtol(sEnd, &sEnd, 10); 

    MeniscusFinderContext M(m_a,m_b); 


    file_stream.getline(buf, sizeof(buf)); 
    while(buf[0] == '#') file_stream.getline(buf, sizeof(buf)); 
    if(atoi(buf) != 255) return 3; 
    file_stream.read((char *)M.m_input_image->m_data ,m_a * m_b); 
    if(!file_stream) { 
     std::cerr << "only got " << file_stream.gcount() << std::endl; 
     return 2; 
    } 
    file_stream.close(); 
return 0; 
} 

編輯:我運行它,有時它運行,而其他它給我的錯誤。似乎是隨機排列的。任何提示都會非常有幫助。 我已經檢查了堆棧溢出中的所有相關答案,但無法找出答案。

+0

請嘗試重新格式化您的文章和您的代碼,這真的很難閱讀。要在Visual Studio中重新格式化代碼,您可以選擇全部(Ctrl + A),然後按CTRL + K + F – user2176127

+0

user2176127現在好嗎? –

+0

'm_data = new uint8_t(m_w * m_h); //深度複製指針數據不會複製任何東西。 –

回答

0
new uint8_t(w*h); 

此分配恰好一個uint8_t,其初始值是w*h

你可能打算:

new uint8_t[w*h]; 

否則,這樣的:

file_stream.read((char *)M.m_input_image->m_data ,m_a * m_b); 

會立刻溢出這個緩衝區。在顯示的代碼中出現了幾次相同的錯誤。與new[]分配

delete m_data; 

東西應該與delete[]被釋放。

總體而言,您的整體方法非常容易出錯。用這種方式來代替手動處理內存,你應該使用std::vector和迭代器。正確使用C++的容器大大降低了發生這類錯誤的可能性。

+0

但我仍然收到此錯誤:Image_Processing(6371,0x100091000)對象0x100600268的malloc:***錯誤:釋放的指針未分配 ***在malloc_error_break中設置斷點以進行調試 –

相關問題