Variable is passed from one thread to another without ensuring that variable stays alive through duration of latter thread
This defect occurs when an automatic or thread local variable is passed by address from one thread to another thread without ensuring that the variable stays alive through the duration of the latter thread.
The defect checker applies to both C11 and POSIX® threads.
An automatic or thread local variable is allocated on the stack at the beginning of a thread and its lifetime extends till the end of the thread. The variable is not guaranteed to be alive when a different thread accesses it.
For instance, consider the start function of a C11 thread with these lines:
int start_thread(thrd_t *tid) {
int aVar = 0;
if(thrd_success != thrd_create(tid, start_thread_child, &aVar) {
...
}
}The thrd_create function creates a child thread with start function
start_thread_child and passes the address of the automatic variable
aVar to this function. When this child thread accesses
aVar, the parent thread might have completed execution and
aVar is no longer on the stack. The access might result in reading
unpredictable values.
When you pass a variable from one thread to another, make sure that the variable lifetime matches or exceeds the lifetime of both threads. You can achieve this synchronization in one of these ways:
Declare the variable static so that it does not go out of stack
when the current thread completes execution.
Dynamically allocate the storage for the variable so that it is allocated on the heap instead of the stack and must be explicitly deallocated. Make sure that the deallocation happens after both threads complete execution.
These solutions require you to create a variable in nonlocal memory. Instead, you can
use other solutions such as the shared keyword with OpenMP's threading
interface that allows you to safely share local variables across threads.
| Group: Concurrency |
| Language: C | C++ |
| Default: Off |
Command-Line Syntax:
LOCAL_ADDR_ESCAPE_THREAD |
| Impact: Medium |