sqc 0.4.13

Software Code Quality - CERT C compliance checker
[metadata]
id = "CON30-C"
type = "recommendation"
category = "CON"
number = 30
title = "Clean up thread-specific storage"
description = """
Thetss_create()function creates a thread-specific storage pointer identified by
a key. Threads can allocate thread-specific storage and associate the storage
with a key that uniquely identifies the storage by calling thetss_set()function.
If not properly freed, this memory may be leaked. Ensure that thread-specific
storage is freed. In this noncompliant code example, each thread dynamically
allocates storage in theget_data()function, which is then associated with the
global key by the call totss_set()in theadd_data()function. This memory is
subsequently leaked when the threads terminate. #include <threads.h> #include
<stdlib.h> /* Global key to the thread-specific storage */ tss_t key; enum {
MAX_THREADS = 3 }; int *get_data(void) { int *arr = (int *)malloc(2 *
sizeof(int)); if (arr == NULL) { return arr; /* Report error */ } arr[0] = 10;
arr[1] = 42; return arr; } int add_data(void) { int *data = get_data(); if (data
== NULL) { return -1; /* Report error */ } if (thrd_success != tss_set(key,
(void *)data)) { /* Handle error */ } return 0; } void print_data(void) { /* Get
this thread's global data from key */ int *data = tss_get(key); if (data !=
NULL) { /* Print data */ } } int function(void *dummy) { if (add_data() != 0) {
return -1; /* Report error */ } print_data(); return 0; } int main(void) {
thrd_t thread_id[MAX_THREADS]; /* Create the key before creating the threads */
if (thrd_success != tss_create(&key, NULL)) { /* Handle error */ } /* Create
threads that would store specific storage */ for (size_t i = 0; i < MAX_THREADS;
i++) { if (thrd_success != thrd_create(&thread_id[i], function, NULL)) { /*
Handle error */ } } for (size_t i = 0; i < MAX_THREADS; i++) { if (thrd_success
!= thrd_join(thread_id[i], NULL)) { /* Handle error */ } } tss_delete(key);
return 0; }
"""
severity = "Medium"
likelihood = "Unlikely"
priority = "P2"
level = "L3"
cert_version = "2016 Edition (Wiki)"
last_modified = "May 05, 2025"

[rules.cert_c.CON30-C]
enabled = true

[references]
wiki = "https://wiki.sei.cmu.edu/confluence/display/c/CON30-C.+Clean+up+thread-specific+storage"