简体   繁体   English

为什么我的代码出现“访问冲突读取位置”错误?

[英]Why do I get an “Access violation reading location” error with this code?

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 . 你没有创建test123 Allocate the structs with new rather than malloc and this will create test123 for you. 使用new而不是malloc分配结构,这将为您创建test123

abc = new StructTest;
Struct1* a1 = new Struct1;

Remember to dispose with delete rather than free . 记得用delete而不是free

In fact, since you are using C++ you should simply stop using malloc . 事实上,由于您使用的是C ++,因此您应该停止使用malloc

It's crashing on this line: 它崩溃在这条线上:

abc->test123.push_back(a1);

The reason is because you allocate it two lines above using malloc . 原因是因为你使用malloc在上面分配了两行。 Therefore, the contents of test123 are uninitialized. 因此, test123的内容未初始化。 So it crashes when you call push_back on it. 所以当你在上面调用push_back时会崩溃。

Do not use malloc, use new. 不要使用malloc,使用new。 malloc does not cause constructors be called so in this case your vector is not a valid object. malloc不会导致构造函数被调用,因此在这种情况下,您的向量不是有效对象。

Because, when you allocate a block with "malloc" it may contain garbage, zeros, or whatever. 因为,当您使用“malloc”分配块时,它可能包含垃圾,零或其他任何内容。

The object test123 is a C++ object, whose constructor has not been executed. 对象test123是一个C ++对象,其构造函数尚未执行。 Try using operator new instead. 尝试使用operator new代替。

Also, while we're on the subject, in C++, there is no need to typedef structs, they will become first-class names automatically. 此外,虽然我们关于这个问题,在C ++中,没有必要typedef自动结构,他们将成为一流的名字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM