Sharath
Sharath

Reputation: 1775

Making sense of the addr2line message with C++ STL

I have been having this rare segfault, and while debugging it, I managed to get the following output from addr2line program.

void std::string::_S_copy_chars<__gnu_cxx::__normal_iterator<unsigned char 
const*, std::vector<unsigned char, std::allocator<unsigned char> > > >
(char*, __gnu_cxx::__normal_iterator<unsigned char const*, 
std::vector<unsigned char, std::allocator<unsigned char> > >,
__gnu_cxx::__normal_iterator<unsigned char const*, std::vector<unsigned char, 
std::allocator<unsigned char> > >)
??:?

Since _S_copy_chars() is a private function in std::string, I am obviously not calling it directly. But I am unable to guess which public function is calling it. If I can figure out the public function, I can zero in on the null de-referencing that is causing the segfault.

I am suspecting the following code...

std::string CInProtocolBase::RetrieveStr(std::vector<unsigned 
char>::const_iterator& iter)
{
    unsigned long sizeOfStr;
    const unsigned char& size = *iter;
    memcpy(&sizeOfStr,&size,4);
    sizeOfStr = 
    boost::asio::detail::socket_ops::network_to_host_long(sizeOfStr);
    std::string str(iter+4,iter+4+sizeOfStr); // <= Could this be culprit??
    iter += (4 + sizeOfStr);
    return str;
}

The Other candidate is this:

std::string CInProtocolBase::VectorToStr(const std::vector<unsigned char>& vec)
{
    return std::string(vec.begin(),vec.end());
}

Upvotes: 0

Views: 269

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

With memcpy(&sizeOfStr,&size,4) I see two problems.

The first is that you copy four bytes from a one-byte variable. That is a clear undefined behavior.

The second is that sizeOfStr might be 8 bytes (on 64-bit systems GCC usually have long being 64 bits). This will let part of the variable be uninitialized and therefore be indeterminate, again leading to undefined behavior.

Use normal assignment and let the compiler properly do the conversion for you:

sizeOfStr = size;

Upvotes: 3

Related Questions