Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get an "Access violation reading location" error with this code?

Tags:

c++

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;
}
like image 364
tandaica0612 Avatar asked Oct 06 '11 09:10

tandaica0612


2 Answers

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.

like image 124
David Heffernan Avatar answered Sep 29 '22 09:09

David Heffernan


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.

like image 20
Mysticial Avatar answered Sep 29 '22 09:09

Mysticial