coredump:将文件内容读取到std :: string

时间:2012-10-23 06:48:15

标签: c++ stl coredump

在将文件内容读取到std :: string时遇到coredump。代码如下:

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

但有时代码导致coredump如下:

...
#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&) ()

从上面的代码片段中,异常在underflow函数中抛出。但我不知道为什么抛出异常。阅读时可能会删除该文件,但代码中的哪个语句可能导致抛出异常?

1 个答案:

答案 0 :(得分:1)

从堆栈跟踪中可以清楚地看出,异常是从content.assign引发的。看起来string::assign是一个调用std::string::_M_replace_dispatch的内联函数。您可以通过查看头文件或使用调试器来检查这一点。这回答了这个问题吗?