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

977 views Asked by At

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.

2

There are 2 answers

3
pilcrow On BEST ANSWER

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.

7
O.C. On

By looking at the source code of pthread_key_create and pthread_key_delete it seems that pthread_key_create is returning a memory location and filling in other fields of "key" structure, which is opaque like everything else in posix.

pthread_key_delete expects the key structure fields to be populated/set with valid data to search for the memory location. So it seems calling pthread_key_delete after a failed pthread_key_create causes undefined behavior. Here is one more link that seems to support by opinion.

How does pthread_key_t and the method pthread_key_create work?

I hope this helps.