I have a bug which seems to cause access to memory which has already been cleared. There are 2 classes - class B (which contains struct instances of class C and unique_ptrs of class D) and Class A which contains a vector of class B objects. Here's the code structure of the area where the bug is caused:
void foo{
A localA(...);
bar(&localA);
baz(localA);
}
void bar(A* a) {
C c1 = constructLocalC1();
D d1 = constructLocalD1();
a.insertB(c1, &d1);
}
Note that insertB will call the constructor for class B - something like:
void A::insertB(C c, D* d) {
bVector.push_back(B(c, d));
}
B::B(C cIn, D* dIn) : c_(cIn) { d_ = make_unique<D>(*dIn); }
B {
public:
B(C c, D* d);
C c_;
std::unique_ptr<D> d_;
}
The implementation of constructLocalC1()
looks something like (similar for constructLocalD1()
)
C constructLocalC1() {
C c1;
c1.blah = computeBlahParameter(); // blah is of type int
c1.bleh = computeBlehParameter(); // bleh is of type double
return c1;
}
The observation is that when baz tries to access (the copy of) c1 present in localA, the values in there are corrupted and not the same as the ones set by bar. My conclusion from this observation is that the vector which stores B is storing an element which has become de-allocated.
I know it is slightly complicated to understand the root cause through the code snippet here, as this is highly abstracted out - glad to provide more specific details which are required.
What are potential pitfalls and causes of memory leaks in this code snippet? What are good ways to approach the debugging?