Mokus
Mokus

Reputation: 10400

When will the data from a vector freed?

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?

Upvotes: 1

Views: 159

Answers (2)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122458

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.

Upvotes: 4

Mark Ransom
Mark Ransom

Reputation: 308206

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.

Upvotes: 3

Related Questions