
mathog wrote
On 22-Apr-2014 21:12, liamw wrote:
int main() { int *p; { int x = 0; p = &x; } return *p; }
I asked about this on the valgrind list and the response was that g++ does not actually allocate by block scope, but rather by function scope. So in terms of what the compiler produces, the preceding program is exactly the same as:
int main() { int *p; int x = 0; p = &x; return *p; }
Well, no. Compilers don't have to (and shouldn't!) allocate local variables, they just put them on the stack (or in a register if it is a POD type that can fit in one).
To see why the scoping code works, I wrote an interesting program that attempts to replicate the compiler's job of local variable allocation. This is the full program: http://paste.ubuntu.com/7332558/ However, for the purposes of this demonstration I'll boil it down to the following:
/* get_sp() is a small function in the full source that retrieves the stack pointer. */ unsigned long& sub() { // sp becomes a pointer to a value on the stack unsigned long* sp = reinterpret_cast<unsigned long*>(get_sp() - PTR_S); // now assign the object *sp = 134; return *sp; }
int main() { printf("value of sub(): %lu\n", sub()); return 0; }
And this will compile and work correctly (print 134). Why!? Isn't the memory deleted when the stack is unwound?! Remember that we returned a reference to the memory, which is like a pointer and is treated like one in assembly. We called get_sp() to get the location of the stack pointer, then we wrote to that location.
When we returned the reference, the stack may have been unwound (and $rip popped into $pc), but the data still exists at the place "sp" points to. We can therefore dereference and even use it, HOWEVER, any further function calls/local variable allocations have /no guarantee *whatsoever*/ of not overwriting this value, potentially with a non-POD type that crashes on dereference. This is why a compiler warning is issued.
-- View this message in context: http://inkscape.13.x6.nabble.com/Clang-address-sanitizer-abort-tp4970295p497... Sent from the Inkscape - Dev mailing list archive at Nabble.com.