2012-09-26 67 views
2

我有代碼如下:Valgrind的 - 可能丟失警告

std::string myName = "BLABLABLA"; 

//check if there are illegal characters 
for (unsigned int i = 0; i < myName.length(); i++) 
{ 
    const char& c = myName[i]; 
    if (!(isalnum(c) || (c == '_') || (c == '-'))) 
    { 
     return 0; 
    }  

} 

這是的valgrind中的線的輸出 「常量字符& C = MYNAME [I];」

==17249== 51 bytes in 1 blocks are possibly lost in loss record 116 of 224 
==17249== at 0x4C2714E: operator new(unsigned long) (vg_replace_malloc.c:261) 
==17249== by 0x602A498: std::string::_Rep::_S_create(unsigned long, unsigned long,  
std::allocator<char> const&) (in /usr/lib64/libstdc++.so.6.0.16) 
==17249== by 0x602A689: std::string::_M_mutate(unsigned long, unsigned long, 
unsigned long) (in /usr/lib64/libstdc++.so.6.0.16) 
==17249== by 0x602AFB5: std::string::_M_leak_hard() (in 
/usr/lib64/libstdc++.so.6.0.16) 
==17249== by 0x602B0A4: std::string::operator[](unsigned long) (in/
/usr/lib64/libstdc++.so.6.0.16) 

我看不出什麼錯這個......

+0

魔鬼在細節中。更具體地說,在GCC的'std :: string'裏面。這不是你的錯。這不是你的錯。 –

+0

@KerrekSB gcc的字符串泄漏? –

+0

@LuchianGrigore:是的。這是refcount業務... –

回答

2

是的,這是可怕的COW實現! 您還可以強制使用const的(因此非不同誘變)超載,像這樣:

std::string const myName = "BLABLABLA"; 

//check if there are illegal characters 
for (unsigned int i = 0; i < myName.length(); i++) 
{ 
    const char& c = myName[i]; 
    if (!(isalnum(c) || (c == '_') || (c == '-'))) 
    { 
     return 0; 
    }  
} 

或者(如果你不想修改原始字符串類型):

std::string myName = "BLABLABLA"; 
std::string const &cref = myName; 
//check if there are illegal characters 
for (unsigned int i = 0; i < myName.length(); i++) 
{ 
    const char& c = cref[i]; 
    if (!(isalnum(c) || (c == '_') || (c == '-'))) 
    { 
     return 0; 
    }  
} 


COW reference,因爲我知道我會寫一些有關它的地方。

相關問題