MISRA.STDLIB.MUTEX.NO_UNLOCK.2023

Missing unlock for mutex variable

MISRA C 2012 AMD4 Rule 22.16: All mutex objects locked by a thread shall be explicitly unlocked by the same thread

Category: Required

Analysis: Undecidable, System

Applies to: C11

Amplification

If a mutex object mtx is locked by mtx_lock(mtx) at a program point p there shall be an explicit mtx_unlock(mtx) for mutex object mtx on all programs paths reachable from p before exiting the thread.

Rationale

When a thread terminates without releasing a lock, that lock may be held for indeterminate time. If the life range of a mutex object ends while there are threads waiting for it the behavior is undefined.

Destroying a mutex on which threads are waiting is undefined behavior.

Note: it is good practice to unlock mutexes in the same function and under the same control dependences in which they have been locked.

Vulnerable code example

Copy
#include <threads.h>
mtx_t mutex;
int thread_func(void *arg)
{
    mtx_lock(&mutex);
    if (arg) {
        return 0; // defect MISRA.STDLIB.MUTEX.NO_UNLOCK.2023
    }
    mtx_unlock(&mutex);
    return 0;
}
int main()
{
    thrd_t tid;
    thrd_create(&tid, thread_func, NULL);
    thrd_join(tid, NULL);
    return 0;
}

See also

Dir 4.13, Rule 22.1

"MISRA", "MISRA C" and "MISRA C++" are registered trademarks of The MISRA Consortium Limited. ​