c++ - Why is this pointer valid when its object should be out of scope? (And some other weird behaviors) -


this question has answer here:

i'm still new c++ , have been studying object scope.
i've tested code below , witnessed weird behaviors.

struct test {     int value, value2;     test() : value(1), value2(10) {}; };   test* gettestpointer() {     test t;     t.value = 20;     return &t; }  int main() {     test* tp = gettestpointer();     int = tp->value;     int b = tp->value2;     cout << << endl;     cout << b << endl;      return 0; } 

output:

20 10 

i thought test t go out of scope dereferencing values in main either throw exception or empty value. why getting valid values if object still alive?

actually tried:

test* tp = gettestpointer(); cout << tp->value << endl; cout << tp->value2 << endl; 

output:

20 18223279 

here value2 acting it's invalid can value fine.
conversely tried reordering them:

test* tp = gettestpointer(); cout << tp->value2 << endl; cout << tp->value << endl; 

output:

10 1459403656 

note none of happened when initiated tp new, expected.

i know never write code in real life got curious why of happening.

  1. when t go out of scope in case?
  2. what ordering of cout have tp dereferencing?
  3. why when save them in buffers can correct values?

you got lucky correct value, in general undefined behavior , compiler should warn this.

try extend example this:

int my_sum(int a, int b) {return + b;} int main() {     int res;     test* tp = gettestpointer();     res = my_sum(1, 2);     int = tp->value;     int b = tp->value2;     cout << << endl;     cout << b << endl;      return 0; } 

you see different output because local scoped test object overwritten function call.

when use new statement, object not created locally, on heap memory , therefore valid when go out of function scope. in case, have use delete, delete object later.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -