最近遇到一个非常有意思的bug,程序总是在 list.push_back() 这行崩溃。代码如下:

    



// 初始化线程池 
void init_threads( int m_thread_number )
{
thread_t *m_threads;

m_threads = new pthread_t(m_thread_number);
assert( m_threads != NULL );

int ret = 0;

// 创建指定数量线程
for(int i=0;i<m_thread_number;i++)
{
ret = pthread_create( m_threads+i,NULL,worker,this );
assert( ret == 0 );

ret = pthread_detach(m_threads[i]);
assert( ret == 0 );
}

// 测试一
std::list<double> list;
list.push_back(40.8);

// 测试二
// new int(5);
}



   

    将push_back()这行代码注释,更换成测试二代码一样会出错。出错堆栈均定位到malloc(),如更换成不分配内存的代码,运行很正常。 看到此,百思不得其解。此时内存是完全足够的,不存在无法分配内存的情况。只有一种可能,程序堆栈被早已损坏。现代OS的容错能力比较强,真正bug处没有立即出错,可能运行在另一台电脑上,会立即出错。

手误将[]写成了(),更改成 new pthread_t[m_thread_number],运行OK