Automatic destroy of global vectors

I have a case where I am declaring an std::vector as global. Precisely, vector is an collection of std::list, which is collection of int.

std::vector<std::list<int*> >
I am making it global in one file under an namespace. Like:

namespace SPACE_1 {
std::vector<std::list<int*> > vec_1;

class CLASS_1 {
// And inside this class I have some functions which
// populates this vec_1
}
}
When my work is done, I clear the vector using this code(inside an function)

std::vector<std::list<int*> >::iterator it = vec_1.begin();
for (; it != vec_1.end(); ++it) {
(*it).clear();
}
vec_1.clear();
Make sense till now?

At the end of main, destructor of that vector gets called, which is fine, and it assert for some reason. Not able to understand why! I understand that it calls destructor but not why does it crashes.

You might say that why I am clearing this up and should be automatically handled when program ends. Yes, I concur but I wanted to understand this case.

Little help?
This:
1
2
3
4
std::vector<std::list<int*> >::iterator it = vec_1.begin();
for (; it != vec_1.end(); ++it) {
(*it).clear();
}
is unnecessary. The lists will be destructed anyway.

it assert for some reason
Well, there is no reason for this, hence something bad must be happen before this.

What are this int pointer good for?
@bhargavah,

I must agree with @coder777.

I tried what I can of your code as posted.

There was no assertion stuffing vec_1 with 50 lists, each with 20 int *.

No problem with or without your "clear up" code.

That said, as @coder777 points out, the destruction of vec_1 is automatic at program exit, which in turn means the destruction of the lists it contains.

The only issue that comes to mind, as of yet, is @coder777's closing question - more specifically, are the int *'s dynamically allocated (are they integer arrays created with new?").

If these int *'s are merely some reference to storage which you know is deleted appropriately, this wouldn't be an issue. If, however, they are arrays, the question that comes to mind is do you intend the list to "own" whatever these int *'s point to? That is the one thing that would require visiting every entry to delete that storage (but not the calls to 'clear' of these containers).

That would probably not be the exact source of the assertion.

Factually, we, out here, have no idea what the assert said. What did the assert apply to, and what code did the assert fire on?

At the end of main, destructor of that vector gets called, which is fine, and it assert for some reason.

The vector asserting is probably just a symptom of heap corruption. The actual cause of the corruption is somewhere else in your code.
Topic archived. No new replies allowed.