Skip to content
Advertisement

Segmentation fault (exit code 139) when using pthread_join

I’m doing some first steps with threads on Linux systems, and i have this error which occures on the base of a program that gets some n argument and creates n number of threads.

Here is the important part of the code:

The function the threads should run:

JavaScript

Important part of code in the main function

JavaScript

Notice the last for loop with the pthread_join function, when i comment it out the program ends fine (exit code 0), but the output is obviously wrong since not all of the threads runs function before the main process exits.

When i don’t comment it out i get segmentation fault (core dumped) when trying to run using the terminal in my Linux OS and Process finished with exit code 139 when running in my IDE (CLion).

I couldn’t find anything i’ve done wrong as it’s a very basic program that shouldn’t have anything hard to find, what is the problem that causes the error?

Advertisement

Answer

You should have used pthread_join(threads[i], NULL); instead of pthread_join(threads[num], NULL);. Suppose, the num is set to 4 via argument. Then threads[num] points to 5th element of array which does not exist as you have allocated an array of only 4 elements.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement