Allan Bruce wrote:
<snip>
>
> This I understand as it is very similar in c. My belief is that
> variablePointer is a pointer to an int. count is declared as an int and
> initialised to 32. variablePointer is then set to point to count, and
> therefore has value 32 when cout is called.
> My problem is then in the following example which is supposedly wrong:
> {
> int *variablePointer;
> {
> int count = 32;
> variablePointer = &count;
> }
> cout << *variablePointer;
> }
Not supposedly - it *is* wrong.
The variable 'count' will go out of scope after you take a pointer to
it, and before you dereference that pointer. The closest analogy I can
think of in C-like code is:
int* varptr = (int*)malloc(sizeof int);
*varptr = 32;
free(varptr);
printf("%d", *varptr);
Since the memory is no longer allocated to an object, the system is free
to use it for anything... and your pointer is no longer valid. The
chances are that you'll find that it has been written to before you get
to dereferencing the pointer. And if you (or the compiled code) do
anything else between count going out of scope and dereferencing the
pointer, then the probability of the value remaining unmodified
approaches zero.
In the specific example you quoted, depending on what's going on behind
the scenes, I'd say you have a fairly good chance that the stack space
you're pointing to still contains the value count had before it went out
of scope. However, relying on this to be true is a fundamentally
*wrong* practice that *will* cause you problems in future.
> I just want to clarigy if I understand why this is wrong.
> variablePointer again is a pointer to an int and has scope within the
> whole of the above function. We then enter a new scope sub-level, and
> count is decalred as an int and initialised to the value of 32.
> variablePointer is set to point to count. We then leave this scope
> level, and when we try to use cout for variablePointer, we are causing
> undefined behaviour. Is this a correct assumption?
Err.. see above
(I must remember to re-read to the bottom before responding... *sigh*)
--
Corey Murtagh
The Electric Monk
"Quidquid latine dictum sit, altum viditur!"