4

我正在使用 POSIX 线程,并且在我的程序结束时,我正在等待加入每个线程。经过一段时间的完美运行后,当我等待线程时,我的代码开始返回一个奇怪的错误。

pthreads threads[C+P];

for(i = 0; i < (C+P); i++)
{
    printf("%d\n", i);  
    pthread_join(threads[i]);
}

如果我删除了 printf 语句,或者将其替换为任何其他 printf 语句、延迟或对 i 的任何其他操作,我仍然会遇到段错误。

我将如何开始调试呢?

4

1 回答 1

7

Inserting printf() call affects memory layout (and thus it can, by pure accident, mask some memory corruption), as well as execution timing (you use threads, so timing is also relevant).

But instead of any sort of guesswork, you should do some regular debugging:

  • run you executable under gdb, this way you should be able to see what exact operation is causing a crash, where is it called from, etc.

  • run it under valgrind - this tool detects a lot of common errors, like accessing free'd memory block, using uninitialized variables, exceeding array/buffer boundaries, etc. It's not uncommon to immediately get exact position of the error with valgrind, I highly recommend it!

于 2012-11-08T00:54:48.927 回答