The C Standard, subclause 7.26.5.6 [ISO/IEC 9899:2011], specifically 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.
This noncompliant code example detaches a thread that is later joined.
#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, 0)) {
/* Handle error */
return 0;
}
if (thrd_success != thrd_join(t, 0)) {
/* Handle error */
return 0;
}
return 0;
} |
This compliant solution does not detach the thread. Its resources are released upon successfully joining with the main thread.
#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, 0)) {
/* Handle error */
return 0;
}
if (thrd_success != thrd_join(t, 0)) {
/* Handle error */
return 0;
}
return 0;
} |
Joining or detaching a previously joined or detached thread causes undefined behavior.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
|---|---|---|---|---|---|
CON41-C | Low | Likely | Low | P9 | L2 |
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
| [ISO/IEC 9899:2011] | Subclause 7.26.5.3, "The |