开发者

Getting SIGSEGV/SIGABRT when allocating memory for a string

Really don't know what to make of this--my program keeps crashing when I am allocating memory for a string, most often in this innocuous bit of code, which in other contexts has never caused a problem:

template <class T>
inline string to_string (const T& t, bool use_fixed = false)
{
    stringstream ss;
    i开发者_Python百科f (use_fixed) ss.setf(ios::fixed, ios::floatfield);
    ss << t;
    return ss.str();
}

Specifically it crashes at 'ss << t'. t was type int, ==0. The last lines of the stack trace look like this (alas, I'm too new to post a screenshot):

0   ??  
1   malloc
2   operator new(unsigned int)
3   std::string::_Rep::_S_create(unsigned int, unsigned int, std::allocator<char> const&)
4   std::string::_Rep::_M_clone(std::allocator<char> const&, unsigned int)
5   std::string::reserve(unsigned int)
6   std::basic_stringbuf<char, std::char_traits<char>, std:allocator<char> >::overflow(int)
...

The only possibly relevant thing different with my program now that I can think of is that it has multiple threads, and launches a child process which has multiple threads and also calls this function. I'm on Ubuntu 10.04. Thanks for your consideration--

Matt


The standard answer when this happens is "you're corrupting the memory allocator internal data structures somehow", so that's why it crashes. Check your array bounds because if you write outside the bonds of a memory block, you might overwrite something that you shouldn't.


Actually Matias Valdenegro gave you the correct answer. However, he did it in a way, that you didn't understand it: He said that you're corrupting the memory allocator's internal data structures somehow. And that's exactly what you were doing. The only thing you didn't understand (and Matias didn't tell you): You're not corrupting the heap in the code you've quoted here. You're corrupting the heap somewhere else. The quoted code just triggers the abort signal, because that's the point where the allocator functions (i.e. the new operator) detects, that your heap got corrupted (somewhere else). And that's exactly why - in opposite to your comment - C++'es std::to_string won't help here at all (it will also SIGABRT if you corrupt the heap) and it's why the bug suddenly disappeared, while you were working on something else elsewhere. You obviously just fixed the bug causing the heap corruption in the first place.

A great tool to find this kind of bug is called valgrind, if you don't know about it yet, you most certainly should change that because it would have told you not only what's going on, but also, where the actual bug resides.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜