lundi 22 juillet 2019

why async() write on temporary variable and no crash happend

This is some code I write to test async() wirte on tempory variables. the function test use async() the execute a function write_A(A* a), and use future.wait_for() to wait the result for a period of time. If it'is timeout, test returns, the A a2 will be freeed at the same time, because it is allocated on stack. The write_A write on A* a would crash. But in fact the program works fine. Why the async executed function write_A can write on freed stack tempory variable?

struct A {
  string name;
  string address;
};

int write_A(A* a) {
  sleep(3);
  a->name = "tractor";
  a->address = "unknow";
  cout <<"write_A return" << endl;
  return 0;
}

void test(A* a) {
   A a2;
  future<int> fut = async(launch::async, write_A, &a2);
  auto status = fut.wait_for(chrono::milliseconds(1000));
  if (status == future_status::ready) {
    int ret = fut.get();
    *a = a2;
    cout <<"succ"<<endl;
  } else {
    cout <<"timeout"<<endl;
  }
}

void test2() {
  A a;
  test(&a);
}

int main ()
{
  test2();
  sleep(5);
  return 0;
}

I expect the program will crash because write_A write on a pointer of object which has beed released when the test returned. But the program output:

timeout

write_A return

Aucun commentaire:

Enregistrer un commentaire