CertC-CON39ΒΆ

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

Required inputs: IR

The C Standard, 7.26.5.6 [ ISO/IEC 9899:2011], states that a thread shall not be joined once it was previously joined or detached. Similarly, subclause 7.26.5.3 states that a thread shall not be detached once it was previously joined or detached. Violating either of these subclauses results in undefined behavior.

Noncompliant Code Example

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

#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:

#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.

Rule Severity Likelihood Remediation Cost Priority Level
CON39-C Low Likely Medium P6 L2
Bibliography
[ ISO/IEC 9899:2011] Subclause 7.26.5.3, "The  thrd_detach Function"
Subclause 7.26.5.6, "The  thrd_join Function"
Excerpt from SEI CERT C Coding Standard: Rules for Developing Safe, Reliable, and Secure Systems (2016 Edition) and SEI CERT C Coding Standard [https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/rules/concurrency-con/con39-c], Copyright (C) 1995-2026 Carnegie Mellon University. See section 9.4. "3rd-Party Licenses" in the documentation for full details.

Possible Messages

Key

Text

Severity

Disabled

already_detached

Target thread is possibly already detached.

None

False

already_joined

Target thread is possibly already joined.

None

False

Options