C++: Pointer not initialized but pointing to a variable -
int main() { int b = 10; int* bpointer; *bpointer = b; cout << *bpointer << endl; cout << bpointer; }
first cout prints 10, second prints 0. how can pointer pointing 0 store value?
as other comments , answers have noted, using uninitialized pointer yields undefined behavior—so shouldn't that. however, seem understand that, you're still curious why see behavior you're observing...
since bpointer
not declared volatile
, compiler can assume *bpointer
cannot change during function scope.
basically, compiler sees assignment
*bpointer = b;
and optimizes line
cout << *bpointer << endl;
into this
cout << 10 << endl;
which can assume equivalent.
the compiler might able deduce program ends @ point, , skips assignment *bpointer
altogether; however, seems bit more farfetched me.
all of platform , compiler combinations tried yielded error, wasn't able confirm explanation—but if you're observing behavior, that's educated guess happened.
update
i able reproduce behavior g++ (gcc) 4.8.3 when compiling -o1
flag. here's relevant assembly1:
main: .lfb975: .cfi_startproc subq $8, %rsp .cfi_def_cfa_offset 16 ; next 3 lines print "10" (via cout) movl $10, %esi movl std::cout, %edi call std::basic_ostream<char, std::char_traits<char> >::operator<<(int) ; next 2 lines print `endl` (via cout) movq %rax, %rdi call std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&) ; next 3 lines print "0" (via cout) movl $0, %esi movl std::cout, %edi call std::basic_ostream<char, std::char_traits<char> >& std::basic_ostream<char, std::char_traits<char> >::_m_insert<void const*>(void const*) movl $0, %eax addq $8, %rsp .cfi_def_cfa_offset 8 ret
as can see, compiler got rid of both variables (i.e., neither b
nor bpointer
has corresponding memory location on stack), , instead assumes constant values (10
, 0
), printed.
again, since using uninitialized pointer results in undefined behavior, compiler free whatever wants... think particular behavior bit strange, it's still "valid" since pointer uninitialized.
1if you're interested, assembly generated this: g++ -o1 test.cpp -s -o /dev/stdout | c++filt
Comments
Post a Comment