GitHub
CERT Secure Coding

CON39-C. Do not join or detach a thread that was previously joined or detached

The C Standard, 7.28.5.6 paragraph 2 [ ISO/IEC 9899:2024 ], states that a thread shall not be joined once it was previously joined or detached.

The termination of the other thread synchronizes with the completion of the thrd_join function. The thread identified by thr shall not have been previously detached or joined with another thread.

Similarly, subclause 7.28.5.3 paragraph 2 [ ISO/IEC 9899:2024 ], states that a thread shall not be detached once it was previously joined or detached.

The thrd_detach function tells the operating system to dispose of any resources allocated to the thread identified by thr when that thread terminates. The thread identified by thr shall not have been previously detached or joined with another thread.

Violating either of these subclauses results in undefined behavior 211 .

Noncompliant Code Example

This noncompliant code example detaches a thread that is later joined.

Non-compliant code
#include <stddef.h>
#include <threads.h>
 
int thread_func(void *arg) {
  /* Do work */
  thrd_detach(thrd_current());
  return 0;
}

int main(void) {
  thrd_t t;

  if (thrd_success != thrd_create(&t, thread_func, NULL)) {
    /* Handle error */
    return 0;
  }

  if (thrd_success != thrd_join(t, 0)) {
    /* Handle error */
    return 0;
  }
  return 0;
}

Compliant Solution

This compliant solution does not detach the thread. Its resources are released upon successfully joining with the main thread:

Compliant code
#include <stddef.h>
#include <threads.h>
  
int thread_func(void *arg) {
  /* Do work */
  return 0;
}

int main(void) {
  thrd_t t;

  if (thrd_success != thrd_create(&t, thread_func, NULL)) {
    /* Handle error */
    return 0;
  }

  if (thrd_success != thrd_join(t, 0)) {
    /* Handle error */
    return 0;
  }
  return 0;
}

Risk Assessment

Joining or detaching a previously joined or detached thread is undefined behavior 211 .

Rule Severity Likelihood Detectable Repairable Priority Level
CON39-C Low Likely No No P3 L3

Automated Detection

Tool

Version

Checker

Description

Astrée
25.10

invalid-thread-operation

Partially checked + soundly supported
CodeSonar
9.1p0

CONCURRENCY.TNJ

Thread is not Joinable

Cppcheck Premium

24.11.0

premium-cert-con39-c
Helix QAC

2025.2

C1776
Parasoft C/C++test

2025.2

CERT_C-CON39-a

Do not join or detach a thread that was previously joined or detached

Polyspace Bug Finder

R2025b

CERT C: Rule CON39-CChecks for join or detach of a joined or detached thread (rule fully covered)
RuleChecker

25.10

invalid-thread-operationPartially checked

Search for vulnerabilities resulting from the violation of this rule on the CERT website .

Bibliography

[ ISO/IEC 9899:2024 ]

Subclause 7.28.5.3, "The thrd_detach Function"
Subclause 7.28.5.6, "The thrd_join Function"