Kam
Kam

Reputation: 6008

Valgrind -- possibly lost warning

I have the code below:

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;
    }      

}

This is the output of valgrind at line "const char& 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)

I do not see anything wrong with this...

Upvotes: 2

Views: 1219

Answers (1)

Useless
Useless

Reputation: 67713

Yes, it's the horrible COW implementation! You can also force use of the const (and therefore non-mutating) overloads like so:

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;
    }      
}

or (if you don't want to modify the original string type):

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;
    }      
}

etc.


COW reference, because I knew I'd written something about it somewhere.

Upvotes: 2

Related Questions