Search code examples
c++stlcoredump

coredump: read file content to std::string


I encounter a coredump when read file content to std::string. Code is list below:

bool readContentFromFile(const char* fileName, std::string& content)
{
    std::ifstream t(fileName);
    if(!t) {
        return false;
    }

    t.seekg(0, std::ios::end);   
    content.reserve(t.tellg());
    t.seekg(0, std::ios::beg);

    content.assign((std::istreambuf_iterator<char>(t)),
                std::istreambuf_iterator<char>());
    return true;
}

But occasionally the code cause coredump as below:

...
#4  <signal handler called>
#5  0x00007f347a0f3945 in raise () from /lib64/libc.so.6
#6  0x00007f347a0f4f21 in abort () from /lib64/libc.so.6
#7  0x00007f347a953504 in __gnu_cxx::__verbose_terminate_handler() () from /usr/lib64/libstdc++.so.6
#8  0x00007f347a951946 in ?? () from /usr/lib64/libstdc++.so.6
#9  0x00007f347a951973 in std::terminate() () from /usr/lib64/libstdc++.so.6
#10 0x00007f347a951a5a in __cxa_throw () from /usr/lib64/libstdc++.so.6
#11 0x00007f347a8ef2ba in std::__throw_ios_failure(char const*) () from /usr/lib64/libstdc++.so.6
#12 0x00007f347a901317 in std::basic_filebuf<char, std::char_traits<char> >::underflow() () from /usr/lib64/libstdc++.so.6
#13 0x00000000004c2751 in char* std::string::_S_construct<std::istreambuf_iterator<char, std::char_traits<char> > >(std::istreambuf_iterator<char, std::char_traits<char> >, std::istreambuf_iterator<char, std::char_traits<char> >, std::allocator<char> const&, std::input_iterator_tag) ()
#14 0x00000000004c281b in std::string& std::string::_M_replace_dispatch<std::istreambuf_iterator<char, std::char_traits<char> > >(__gnu_cxx::__normal_iterator<char*, std::string>, __gnu_cxx::__normal_iterator<char*, std::string>, std::istreambuf_iterator<char, std::char_traits<char> >, std::istreambuf_iterator<char, std::char_traits<char> >, std::__false_type) ()
#15 0x00000000004bf225 in readContentFromFile(char const*, std::string&) ()

From the above code snippets, exception is throwed in underflow function. But I have no idea why throw exception. The file maybe removed when reading, but which statment in code maybe cause throwing exception?


Solution

  • Pretty clear from the stack trace that the exception is being thrown from content.assign. Looks like string::assign is an inline function which calls std::string::_M_replace_dispatch. You could check this by looking at the header files, or using a debugger. Does that answer the question?