2014-09-18 87 views
-6

我正在寫一個程序與USB LCD顯示器(風暴5100-0103)交談,迄今爲止一切工作正常,除了我有一個內存泄漏的地方。C++內存泄漏使用char *

mainLoop: while (true) { 
    // Get the line 
    std::getline(std::cin,stringIn); 

    if (stringIn.find("~") == string::npos || stringIn.empty()) 
    { 
     continue; 
    } 

    // split string to get line data and line number 
    string data; 
    int lineNo; 

    // get the data portion 
    data = stringIn.substr(0,stringIn.find("~")); 

    // create a string for line number 
    string lineNoString = stringIn.substr(stringIn.find("~") + 1, stringIn.length()); 

    // get line number 
    lineNo = atoi(lineNoString.c_str()); 

    // Create a char array to pass to the displaya 
    char *cstr = new char[data.size() + 1]; 
    std::copy(data.begin(), data.end(), cstr); 
    cstr[data.size()] = '\0'; 

    // Write line to the display 
    retval = usbDisplayPtr->DrawString(0, lineNo, 1, cstr, USBDisplayApi::FONT6X16, 3000); 

    cout << retval + "\n"; 

    delete[] cstr; 
} 

任何幫助將不勝感激。

+0

顯示您的功夫 – Steve 2014-09-18 18:52:44

+1

您是否嘗試過valgrind? – taocp 2014-09-18 18:52:49

+0

好像應該刪除cstr;而不是刪除[]給我 – Steve 2014-09-18 18:54:31

回答

0

你有你的

char *cstr = new char[data.size() + 1]; 

和相應的

delete[] cstr; 

這些實施方式是否正確(匹配new[]delete[])。
你的代碼中沒有其他地方在堆上分配內存,而且我也沒有看到任何cstr被修改的地方。

所有這些建議你不要有內存泄漏,或至少,不在你在這裏提交的代碼。

如果你認爲你有內存泄漏,你應該確認它。檢查Valgrind的輸出(或合適的替代方法)。