1

I have the following code

void test(MyDataType * t)
{
   vector<MyDataType> tmp;
   tmp.push_back(MyDataType(2,24));
   t = tmp.data();
}

void test2()
{
    MyDataType * t;
    test(t);
    // Do some stuff with the data pointed by t
}

When will the data stored in the vector freed? It is out of scope after the test function call end. Is that correct?

Mokus
  • 10,174
  • 18
  • 80
  • 122
  • 3
    `t` is by-value to `test`, so `t = ...` is pointless, and means nothing to the caller anyway. There is nothing "out of scope" in this code, since the value of `t` in `main` is as indeterminate *after* the call to `test` as it was before. An easier-to-understand example would be `MyDataType *test() { ... return tmp.data(); }` and `t = test();` in `main()`. That's is also much clearer to see a genuine dangling pointer, which it certainly would be. – WhozCraig Nov 14 '19 at 15:59
  • 2
    First of all your signature would have to be `void test(MyDataType*& t)` for this idea to work. But more importantly, yes the vector `tmp` falls out of scope and is destroyed at the end of `test` so `t` is now a dangling pointer that points to a destroyed obect – Cory Kramer Nov 14 '19 at 15:59
  • very related/maybe dupe: https://stackoverflow.com/questions/21568072/should-i-always-call-vector-clear-at-the-end-of-the-function – NathanOliver Nov 14 '19 at 15:59
  • related: https://stackoverflow.com/a/6445794/5980430 . Also note what @ WhozCraig said – apple apple Nov 14 '19 at 16:01
  • It isnt nice at all to change the question substantially after you got answers. Please do not fix the question. Corrections go to answers not questions – 463035818_is_not_an_ai Nov 14 '19 at 16:04
  • look, both answers address the problem you wanted to ask for and the additional problem in your code that only slipped in by accident. By fixing the second in your question you invalidate both answers. – 463035818_is_not_an_ai Nov 14 '19 at 16:05
  • I switch back, but actually I wanted to ask what @CoryKramer wrote. – Mokus Nov 14 '19 at 16:06
  • as I wrote, both answers do address this question – 463035818_is_not_an_ai Nov 14 '19 at 16:07

2 Answers2

4

When will the data stored in the vector freed? It is out of scope after the test function call end. Is that correct?

Yes correct.

If you would return the pointer from the function it would be a dangling pointer.

However, there is another subtle problem in your code: You pass the pointer t by value, hence the assignment inside test will have no effect on the t in main. If you use t in main you will probably get a segfault not because the vector is already out of scope, but because you never initialized the t in main.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
3

Yes, the destructor for the vector object tmp should free the storage. Your program exhibits undefined behavior, or at least it would if you passed the pointer out properly.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622