Can anyone tell me why I get "Access violation reading location " with this code example? And how can i fix this?
#include <vector>
using namespace std;
struct StructTest;
struct Struct1;
typedef struct Struct1{
StructTest* test;
} Struct1;
typedef struct StructTest{
vector<Struct1*> test123;
} StructTest;
static StructTest* abc;
int test(){
abc = (StructTest*) malloc(sizeof(StructTest));;
Struct1* a1 = (Struct1*) malloc(sizeof(Struct1));
a1->test = abc;
abc->test123.push_back(a1);
return 0;
}
int main(){
test();
return 0;
}
You didn't create test123. Allocate the structs with new rather than malloc and this will create test123 for you.
abc = new StructTest;
Struct1* a1 = new Struct1;
Remember to dispose with delete rather than free.
In fact, since you are using C++ you should simply stop using malloc.
It's crashing on this line:
abc->test123.push_back(a1);
The reason is because you allocate it two lines above using malloc. Therefore, the contents of test123 are uninitialized. So it crashes when you call push_back on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With