Memory allocation order in c++ -
i've written following code trying solve challenge requests array-like structure without using them:
#include <iostream> int main(){ int x = 132,y = 33,z = 87; int *i = &x; std::cout << x << " " << y << " " << z << "\n"; std::cout << &x << " " << &y << " " << &z << "\n"; std::cout << << " " << i-1 << " " << i-2 << "\n"; std::cout << *i << " " << *(i-1) << " " << *(i-2) << "\n"; }
i found difference between 2 variables' addresses (&y-&x) -1 , i've adapted code subsequently don't understand why last defined variable allocated "before" (meaning, previous address).
i have think &y-&x = 1, honestly.
can give me few pointers? (no pun intended :p) oh, know code bad practice - have drawbacks or exceptions?
thank in advance
this practice bad can get.
the stack layout not specified; if variable has on-stack representation (which may not have, if don't take variable address , optimizer moves registers), order between variables , padding (i.e. difference between pointers) not specified.
you can pointer local variable, can't pointer arithmetics on - undefined behavior (unless, of course, we're talking local array variable).
finally, there @ least 1 platform abs(&y - &x) never 1 (because stack vars 16b-aligned).
Comments
Post a Comment