pthreadsposixpthread-key-create

What happens if pthread_key_delete is called on a key after a failed pthread_key_create?


Suppose the following code:

pthread_key_t key;
pthread_key_create(&key, NULL);    /* failure here */
pthread_key_delete(key);

If pthread_key_create fails, is the call to pthread_key_delete considered undefined behavior? How about if pthread_key_create is commented out?

The pthread_key_delete section of the POSIX standard states:

The pthread_key_delete() function shall delete a thread-specific data key previously returned by pthread_key_create().

Since pthread_key_delete expects a thread-specific data key previously returned by pthread_key_create, I'm afraid calling pthread_key_delete on a key that was not returned by pthread_key_create can lead to undefined behavior.


Solution

  • Yes, it is implicitly undefined behavior, to the extent that the standard you link doesn't define what happens in that use case.

    The SUSv7, however, is explicit in its discussion of pthread_key_delete, saying plainly in its CHANGE HISTORY for Issue 7 that:

    The [EINVAL] error for a key value not obtained from pthread_key_create() or a key deleted with pthread_key_delete() is removed; this condition results in undefined behavior.