While using pthread_key_create() to prepare a key to be used by various threads to maintain thread specific data, ensure that the thread specific data stored for a key is cleaned up when the thread exits; otherwise, there could be potential memory leaks or misuse of data.
...
This code example is an improvement over the above sample where we try to avoid a memory leak. However, even if the address of the data is known, it could still lead to a potential vulnerability. If, for any reason, the data received from an arbitrary function, get_data(), is NULL, a call to free( pthread_getspecific(key)) would be equivalent to free(NULL), for which the compiler takes no action, according to the standard. This solution, however, does not avoid a call to free() when there is no thread specific data, which is not unsafe but can be avoided (as shown in the subsequent compliant solution).
...