Mat*_*ips 2 c++ string malloc new-operator
真的不知道该怎么做 - 当我为字符串分配内存时,我的程序不断崩溃,最常见的是在这段无害的代码中,在其他上下文中从未引起过问题:
template <class T>
inline string to_string (const T& t, bool use_fixed = false)
{
stringstream ss;
if (use_fixed) ss.setf(ios::fixed, ios::floatfield);
ss << t;
return ss.str();
}
Run Code Online (Sandbox Code Playgroud)
具体来说,它在 'ss << t' 崩溃。t 是 int 类型,==0。堆栈跟踪的最后几行看起来像这样(唉,我太新了,无法发布屏幕截图):
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)
...
Run Code Online (Sandbox Code Playgroud)
现在我能想到的唯一可能与我的程序不同的事情是它有多个线程,并启动一个具有多个线程的子进程并调用此函数。我在 Ubuntu 10.04 上。谢谢你的考虑--
马特
发生这种情况时的标准答案是“您正在以某种方式破坏内存分配器内部数据结构”,这就是它崩溃的原因。检查你的数组边界,因为如果你在内存块的绑定之外写入,你可能会覆盖一些你不应该覆盖的东西。