I am fairly new to C++ and I keep getting segmentation fault with pointer assignment with code similar to the following, I know it means I’m accessing memory that hasn’t been allocated, but I don’t see where:
I have two classes:
class ClassA{ //class a decl.
ClassB** oArray;
unsigned int x;
public:
ClassA(unsigned int X);
void oMember(ClassB* classb);
}
ClassA::ClassA(unsigned int X){ //Constructor for class a
x = X;
oArray = new ClassB* [x];
for (unsigned int i = 0; i < x; i++){
oArray = NULL;
}
}
class ClassB{ //rough decl of class B
public:
getId();
}
I have a class member function that takes in a pointer to another class like this:
void ClassA::oMember(ClassB* classb){
unsigned int cID = classb.getId(); //defined in class b
oArray[cID] = classb; //if cID is less than x defined in constructor, is this legal?
}
I just want to point the cIDth member of the array to classb.
I keep getting segmentation fault with an assignment similar to the above. I don’t quite know why, I printed the cID and it is definitely less than the size of the array we declared in ClassA’s constructor.
Why is that assignment illegal, or why am I getting a segmentation fault?
As we realized in the chat, I just record the problem here for the reference.
The problem lies in the piece
RegisteredVMs is allocated and immediately set to NULL.
This pointer is accessed later in the VMregister() function which causes the seg. fault.
Pointers are hard and very error-prone. Use them only if there is no other way. Since this is a homework problem and since you says you have no say on the interface, I see that you have to use them.