Am I right in thinking it is OK for a thread to access a variable that exists in the stack of another thread?
This is assuming the function in which the stack variable was instantiated has not yet returned.
I think I read somewhere that threads should only share heap memory but I'm now questioning whether that is correct?
This is using POSIX pthreads in C.
Strictly speaking, it's an implementation-defined behaviour whether you are allowed to access the stack variable (variable with automatic storage duration) of another thread from a C11 perspective which provides thread support (but the interfaces are different to POSIX threads), assuming that stack variable is still alive (e.g., you pass an address of a local variable from main function to another thread created via pthread_create
and the main returns exits by calling pthread_exit
.Thus the variable passed to the thread is gone and it would be undefined behaviour. This is no different to using pointer to local variables from other function after that function has returned - threads or not).
But in practice, this is likely to work on most (all?) POSIX thread implementations. I am not aware of any POSIX implementation where this isn't supported.
Looking at the POSIX standard, it actually requires that access to automatic variables be supported:
A single flow of control within a process. Each thread has its own thread ID, scheduling priority and policy, errno value, floating point environment, thread-specific key/value bindings, and the required system resources to support a flow of control. Anything whose address may be determined by a thread, including but not limited to static variables, storage obtained via malloc(), directly addressable storage obtained through implementation-defined functions, and automatic variables, are accessible to all threads in the same process.
(emphasis mine).
So this should be fine on any POSIX implementation.