Question

My question is whether or not I am seeing strange program behaviour due to the inner vector going out of scope (being destroyed) of the loop below

Due to the amount of data produced, it's quite hard to test, so I was wondering if someone could straight up give me an answer

I have a large (STL) vector or pairs, which in turn contains an int and a vector

vector<pair<int, vector<int>>> vectorOfmyTypes

I resize some data

vectorOfmyTypes.reserve(1000000)

Inside a loop I generate a pair>, where the vector has variable length. I have found when I declare vector on the stack, I get some odd behaviour later in my program, but declaring it on the heap fixes it.

For example, the code below:

while( <1000000) {
vector<int> stackVector;
stackVector.push_back(1);
vectorOfmyTypes.pushback(make_pair(1,stackVector);
}

I was under the impression that the object lifetime would all be managed for me by the STL vector object. Is this incorrect? Does vectorOfmyTypes actually still contain a valid stackVector when it loses scope?

I wish to avoid using the heap as possible, as I don't want to have to clear up memory/deal with memory leaks.

Please let me know what you think

Thanks

Was it helpful?

Solution

First of all always show code examples that can be compiled without errors.

The code your showed is irrelevant relative to the error you got.

In this non-compiled example

while( <1000000) {
vector<int> stackVector;
stackVector.push_back(1);
vectorOfmyTypes.pushback(make_pair(1,stackVector);
}

the lifetime of local object stackVector has nothing common with the lfetime of the element of vector vectorOfmyTypes that is added to the vector by using the push_back..

I only can guess that it seems that you placed in the vector a pointer to a local vector. In this case indeed the lifetime of the local vector influenced on the validation of the pointer.

For example

std::vector<std::pair<int, std::vector<int> *>> vectorOfmyTypes;

size_t i = 0;
while ( i < 1000000 ) 
{
    std::vector<int> stackVector;
    stackVector.push_back( i++ );
    vectorOfmyTypes.push_back( std::make_pair( 1, &stackVector );
}

OTHER TIPS

Since there are no pointers involved indeed your assumption is right: when the vector on stack goes out of scope it's destroyed, as well as all contained data.

But since you allocated quite a lot of data in small chunks (many vector of size 1) memory could become fragmented and not appear to decrease from the OS point of view, it's normal behaviour.

If you have another problem please describe it more precisely.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top