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;
}
It’s crashing on this line:
The reason is because you allocate it two lines above using
malloc. Therefore, the contents oftest123are uninitialized. So it crashes when you callpush_backon it.