I’m using a bit of legacy type code that runs on a framework, so I can’t really explain whats going on at a lower level as I don’t know.
However my code creates an array of objectives.
int maxSize = 20;
myObjects = new Object*[maxSize+1];
myObjects[0] = new item1(this);
myObjects[1] = new item2(this);
for(int i=2; i != maxSize+1; i++){
myObjects[i] = new item3(this);
}
myObjects[maxSize+1] = NULL;
If maxSize is larger than 30 I get a whole load of errors I’ve never seen. Visual Studio draws up an error in xutility highlighting:
const _Container_base12 *_Getcont() const
{ // get owning container
return (_Myproxy == 0 ? 0 : _Myproxy->_Mycont);
}
I’ve never used Malloc before, but is this where the problem lies. Should I be assigning using it to avoid this problem?
The absolute value of
maxSizeis probably not a culprit: allocating 30 pointers should go without trouble on any computer, including most micro-controllers. Usingmallocis not going to change anything: you are doing your allocation the way you’re supposed to do it in C++.Here is the likely source of your error:
You have allocated storage for
maxSize+1items, so the valid indexes are between0andmaxSize. Writing one past the last element is undefined behavior, meaning that a crash could happen. You got lucky with 20 elements, but 30 smoked out this bug for you. Usingvalgrindutility is a good way to catch memory errors that could cause crashes, even if they currently don’t cause them.