下面的代码是否有可能产生未定义的行为?
unsigned int total_threads = 10;
vector<thread> t(total_threads);
unsigned int *nums = (unsigned int*)calloc(total_threads, sizeof(int));
for(unsigned int i = 0; i < 1000; i++)
{
for(unsigned int j = 0; j < total_threads; j++)
t[j] = thread(func_, std::ref(nums[j]));
for(unsigned int j = 0; j < total_threads; j++)
t[j].join();
for(unsigned int j = 0; j < total_threads; j++)
{
cout << nums[j] << " ";
nums[j] = 0;
}
}
答案 0 :(得分:4)
是的,因为calloc可能会失败。检查返回值或使用std :: vector。