简体   繁体   English

错误显示C ++中的访问冲突

[英]Error Showing Access Violation in C++

struct root
{
    struct Qgroup
    {
        struct Qpost
        {
            struct Qcomment
            {
                struct Qcomment *next;
                int likes;
                int address;
            } QComment[100];
            int likes;
            int comments;
            int address;
        } QPost[100];
        int address;
        int posts;
        int users;
    }QGroup[8];
}*Root = (struct root *)malloc(sizeof(struct root *));

Getting the Access Violation Error at the following line. 在下面的行中获取访问冲突错误。

for(int i=0;i<5;i++)
Root->QGroup[i].address = i*128+1024*1024;

Please help me out of this? 请帮帮我吗? I tried both static allocation and dynamic allocation, but both failed in reading the data given in above loop. 我尝试了静态分配和动态分配,但是都无法读取上述循环中给出的数据。 This error is from the starting of the execution after main() 此错误是从main()之后的执行开始开始

Your problen is the memory allocation: 您的问题是内存分配:

malloc(sizeof(struct root *));

You allocate memory for a pointer, which is only 4 or 8 bytes on most modern systems. 您为指针分配内存,在大多数现代系统中,该内存只有4或8个字节。

I don't really see a need to use a pointer here in the first place. 我真的没有发现首先需要在这里使用指针。

Root = malloc(sizeof(struct root *));

This has to correct as follows: 这必须更正如下:

Root = (struct root *)malloc(sizeof(struct root ));

No need to cast to struct root * since malloc returns a void pointer and you can assign it to any other type in C. But in case of C++ you need to cast as you did. 无需强制转换为struct root *因为malloc返回一个void指针,您可以将其分配给C中的任何其他类型。但是对于C ++,则需要像以前一样强制转换。

In case of C++ it is always better to use new and delete instead malloc and free . 对于C ++,总是最好使用newdelete而不是mallocfree So you can simply the usage as follows: 因此,您可以简单地使用如下:

 Root = new root ;

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

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