Hi Daniel,
first: please do not top post with a full quote of the former post.
Pick those sentences you answer to and put your answer or question
underneath that sentence. That helps keeping track of the real
questions. Delete the rest of the post which is not relevant any more.
Just look below: your sentence is just a fragment which does not
make any sense on its own anymore. People would need to read all
the old posts to get the content again - not many do -> post ignored
I just did some research. It seems that automatic stack variables are
basically variables of local scope that is allocated automatically
and on a stack. It's what Sven said is opposed to a heap allocated
variable. Is that not correct?
Yes automatic stack variables are value types in a scope and they can
only be used in that scope and deeper but not on outside scopes.
Typically you find errors like returning a stack variable by reference
or by pointer from a function to the caller.
int* foo()
{
int i = 0; // this is on the stack
int* p = &i; // this is a pointer on the stack
*p = 42; // now i will contain the value 42
return p;
}
The caller of foo would get a pointer to an int on a stack location
which is not valid any more.
So whenever you want to pass data from an inner scope to an outer
scope or between threads you will need heap or some global data.
But accessing global or heap data concurrently from different threads
poses risks. A typical case two thread increment a global variable:
GLOBAL contains value 1 when we start
Thread A reads the value of GLOBAL and finds 1
(thread switch)
Thread B reads the value of GLOBAL and still finds 1
(thread switch)
Thread A increments GLOBAL by 1 and so puts 2 back
(thread switch)
Thread B does another increment by 1 but on its old value 1 so
2 is written back to GLOBAL instead of 3
So you need to synchronize access from multiple threads to that
global variable.
If on the other hand you do have private state that no other part of
your code needs to touch then it is good to use stack variables as
you do not need to synchronize access any more.
This is a complex theme and you are not the first to ask. There are
many books and I guess many code samples/articles around in the
internet. To really understand the matter I would recommend that
you just try some code samples, especially those without synchro-
nization to see practically what the results are. That helps a lot to
better understand the problems.