2011-09-22 142 views
6

Valgrind抱怨substr調用。Valgrind錯誤的原因是什麼?

string Message::nextField(string& input) { 
    int posSeparator = input.find_first_of(SEPARATOR); 
    string temp; 
    temp = input.substr(0, posSeparator); //Error points to this line 
    input.erase(0, posSeparator + 1); 
    return temp; 
} 

錯誤雲:在12個塊
290個字節中記錄損失11
什麼該函數基本上是解析輸入,返回由分隔符隔開的字符串的部分絕對丟失。這個功能是從另一個類的方法調用,並且有一個定義:

void doSomething(string input) { 
    input.erase(0,2); 
    string temp = nextField(input); 
    this->room = atoi(temp.c_str()); 
    temp = input; 
    this->money = atoi(temp.c_str()); 
} 

沒有別的怪異或足夠重要,包括在這裏。 我從Eclipse Indigo的Valgrind分析中使用Valgrind的默認設置。 任何想法?

+3

你在編譯期間是否優化?如果是這樣,不要。這導致了valgrind的大量虛假報告。 –

+0

你可能會寫'string temp = input.substr(0,posSeparator);'來初始化字符串而不是分配給它。但是,與您的問題無關,這並不明顯。 –

+0

@DavidHammen不,我不是。 – Erandros

回答

0

您不檢查posSeparator實際上是否與string :: npos不同 - 這可能會導致擦除中的問題。這是一個狂野的鏡頭,但它可能會修復一個錯誤。

1

您的源代碼中可能有其他錯誤。我試着用下面的代碼複製錯誤:

#include <string> 
#include <iostream> 
#include <cstdlib> 

using namespace std; 

const char SEPARATOR = ':'; 

struct Foo 
{ 
public: 
    int room; 
    int money; 

    void doSomething(string input) { 
     input.erase(0,2); 
     string temp = nextField(input); 
     this->room = atoi(temp.c_str()); 
     temp = input; 
     this->money = atoi(temp.c_str()); 
    } 

    string nextField(string& input) { 
     int posSeparator = input.find_first_of(SEPARATOR); 
     string temp; 
     temp = input.substr(0, posSeparator); //Error points to this line 
     input.erase(0, posSeparator + 1); 
     return temp; 
    } 
}; 

int main() 
{ 
    Foo f; 
    f.doSomething("--234:12"); 
    std::cout << f.room << " - " << f.money << std::endl; 
} 

然後Valgrind的一然:

valgrind --tool=memcheck <executable> 

輸出功率爲:

HEAP SUMMARY: 
    in use at exit: 0 bytes in 0 blocks 
    total heap usage: 2 allocs, 2 frees, 61 bytes allocated 

All heap blocks were freed -- no leaks are possible 

For counts of detected and suppressed errors, rerun with: -v 
ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4) 

所以,很可能你的問題不是在這部分代碼

2

這可能不是您代碼中的錯誤。由於C++標準庫的實現細節,可能會報告此錯誤。爲了驗證這一點試着從Valgrind FAQ如下:

隨着GCC 2.91,2.95,3.0和3.1,使用STL 與-D__USE_MALLOC編譯所有源。謹防!這已從版本3.3開始,從GCC中刪除。

使用GCC 3.2.2及更高版本,在運行程序之前,應該導出環境變量 GLIBCPP_FORCE_NEW。

對於GCC 3.4及更高版本,該變量已更名爲 GLIBCXX_FORCE_NEW。

相關問題