I am using POSIX threads, and at the end of my program, I am waiting to join each of the threads. After some time of running perfectly well, my code started returning a weird bug when I was waiting for the threads.
pthreads threads[C+P];
for(i = 0; i < (C+P); i++)
{
printf("%d\n", i);
pthread_join(threads[i]);
}
If I remove the printf statement, or replace it with any other printf statement, a delay, or any other operation on i, I still get a segfault.
How would I start debugging this?
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!