I checked out this thread before posting here: How to avoid memory leaks when using a vector of pointers to dynamically allocated objects in C++?
Basically, I have some vectors of pointers that point to dynamically-allocated objects:
vector<MyType*> a;
a.push_back(new MyType());
These vectors are private instance variables of a few classes I'm writing, and the dynamically-allocated objects are destroyed in the classes' destructors by iterating thru the vectors and calling delete
on each pointer.
It all works fine most of the time, but every once in a while a pointer in one of these vectors becomes invalid and causes a segfault
when my code attempts to use it. I'm having trouble figuring out why these pointers occasionally break.
Are there any reasons why the dynamically-allocated object's address would change and cause the pointers to become invalid?
I can try to post actual code if necessary.
EDIT:
Ok I have a number of things going on here. There are two custom classes: VisaLane
and VisaResource
. VisaLane
contains a vector<VisaResource*>
of pointers to VisaResources created using new VisaResource()
.
Each VisaLane
is also created using new VisaLane()
whose pointers are stored in a vector<VisaLane*>
.
This is one example of how the pointer gets corrupted. Item 0 in the vector has inaccessible members:
resources_ <3 items> std::vector<VisaResource*>
[0] VisaResource
function_ <not accessible> std::string
name_ <not accessible> std::string
state_ VisaResource::FREE VisaResource::VisaResourceState
value_ 6998928 uint
[1] VisaResource
function_ "lane_clksel" std::string
name_ "m1_lane0_clksel" std::string
state_ VisaResource::FREE VisaResource::VisaResourceState
value_ 0 uint
[2] VisaResource
function_ "lane_bypass" std::string
name_ "m1_lane0_bypass" std::string
state_ VisaResource::FREE VisaResource::VisaResourceState
value_ 0 uint
visa_res_itr __gnu_cxx::__normal_iterator<VisaResource**, std::vector<VisaResource*>>