Automatic or thread local variable escaping from a thread
Variable is passed from one thread to another without ensuring that variable stays alive through duration of latter thread
Since R2020a
Description
This checker is deactivated in a default Polyspace® as You Code analysis. See Checkers Deactivated in Polyspace as You Code Analysis (Polyspace Access).
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.
Risk
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.
Fix
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.
Examples
Result Information
Group: Concurrency |
Language: C | C++ |
Default: Off |
Command-Line Syntax:
LOCAL_ADDR_ESCAPE_THREAD |
Impact: Medium |
Version History
Introduced in R2020a
See Also
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)