Re: Weird behavior with uninitialized data
Hakusa@gmail.com () wrote (abridged):
What got weird is when I started toying around with how C++ (or at
least gcc's interpretation) handled uninitialized data:
Integer based types seemed to auto-initialize to some random number
(I'm guessing what was there before they were allocated to that
spot). Then, when I do x++ in the cout, it reads as zero, then
the next time I put it in a cout, another seemingly random number.
It's not very clear what your code is doing. If you are using
heap-allocated objects after they have been deleted, something else might
be using the same memory and changing it from under you. If you are
allocating, outputting, deleting, allocating, and outputting again, then
something else might change the memory while it didn't belong to you. If
it is stack memory (eg you are returning from and recalling the function
which declares it), there might be other functions (perhaps hidden,
compiler-generated ones) which reused that part of the stack meanwhile.
If the memory belongs to you and nobody else the whole time, eg:
{
int x;
cout << x;
cout << x++;
}
then perhaps the compiler has taken advantage of the undefined behaviour
to omit a load instruction. In other words, the values output might not
correspond to x's memory at all. You'd have to use a disassembler or
debugger to get real insight.
Accessing uninitialised variables is undefined behaviour, so the compiler
can do whatever it likes. Generally the compiler just assumes it won't
happen at all, so despite what I wrote above I wouldn't expect the
compiler to optimise uninitialised loads, but I suppose it might fall out
of liveness analysis or something.
-- Dave Harris, Nottingham, UK.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]