Search code examples
c++runtime-error

C++ Runtime Error 0xC0000005 Caused By Object Inside Struct


While working on a C++ project, a runtime error (0xC0000005) showed up. I managed to locate the problem and encapsulate it in the code below.

#include <iostream>

using namespace std;

class TestC{
    public:
    string test1[20];
    string test2[10];

    void initArrays(){
        cout << "init start\n";
        for(int i=0;i<20;i++){
            cout << i << endl;
            this->test1[i] = "initialized";
        }
        cout << "first for complete\n";
        for(int i=0;i<10;i++)
            this->test2[i] = "initialized";
        cout << "init finished\n";
    }
};


struct TestS{
    int anint;
    int anotherint;
    TestC obj;
};


int main(){

    cout<<"Check :\n";
    struct TestS *struct_instance = (struct TestS*) malloc(sizeof(struct TestS));
    struct_instance->obj.initArrays();
    cout<<"Ok Struct";

    return 0;
}

Basically the error is only thrown when initArrays() is called through the TestC object located inside struct TestS.

If initArrays() is called from an object created inside main(), like below, everything works fine.

int main(){
    TestC classObj;
    classObj.initArrays();
}

Despite being able to locate the problem, I have been unsuccessful in fixing it.

Does anyone know what would do the trick?

I am using the Code::Blocks IDE

NOTE: Creating the TestC object in main() and only maintaining a pointer to it within the struct, is not a suitable solution for the actual project.


Solution

  • You're using malloc to allocate a structure that contains a class, TestC. This means the TestC constructor won't run and the test1 and test2 arrays won't be correctly initialized.

    Instead, use new:

    TestS *struct_instance = new TestS;
    

    You should never use malloc to allocate and type that is a C++ class, or contains a C++ class.