简体   繁体   English

为什么在以下代码中出现分段错误?

[英]Why do I get segmentation fault in the following code?

Nothing gets printed in my code. 我的代码中没有任何内容。 No compiler issue. 没有编译器问题。 Why doesn't it print anything? 为什么不打印任何内容? I get no warning either. 我也没有警告。

    #include <stdio.h>
    #include <string.h>

    int main() 
    { 
        struct site 
        { 
            int no_of_pages;
            char name[20];
        }; 
        struct site *ptr;
        ptr->no_of_pages = 665;
        printf("%d\n",ptr->no_of_pages); 

        char array[20];
        strcpy(array, "hello");
        strcpy(ptr->name, "Singularity");
        printf("%s\n",ptr->name);   
        return 0; 
}

Yes, there is a warning which points out the root of your problem: 是的,有一条警告指出了问题的根源:

$ cc -Wall test.c 
test.c:13:5: warning: variable 'ptr' is uninitialized when used here
      [-Wuninitialized]
    ptr->no_of_pages = 665;
    ^~~

首先初始化指针

struct site *ptr = malloc(sizeof(struct site));

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

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