我在对我看来完全有效的代码上遇到了段错误。
这是一个最小的重新创建示例:
#include <iostream>
#include <thread>
void func()
{
/* do nothing; thread contents are irrelevant */
}
int main()
{
for (unsigned idx = 0; idx < 1000; idx++)
{
std::thread t(func);
void* buffer = malloc(1000);
free(buffer);
t.join();
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我进行了打印,以检查哪个迭代失败;我在第292次迭代中遇到了细分错误。
我使用了gcc-linaro-4.9.4(从这里获取:https ://releases.linaro.org/components/toolchain/binaries/4.9-2017.01/arm-linux-gnueabihf/ )。
我这样编译程序:
arm-linux-gnueabihf-g++ -std=c++11 -std=gnu++11 -lpthread -pthread main.cpp -o main.out
Run Code Online (Sandbox Code Playgroud)
我尝试在gcc-linaro-6.5中重新创建它,但那里没有问题。
知道为什么会这样吗?
编译此代码时没有警告/错误。
在strace下运行它并没有什么特别的。
在GDB下运行它可以发现分段错误发生在free函数中:
Thread 1 "main.out" received signal SIGSEGV, Segmentation fault.
_int_free (av=0x76d84794 <main_arena>, p=0x1e8bf, have_lock=0) at malloc.c:4043 …Run Code Online (Sandbox Code Playgroud)