Segmentation fault [duplicate]

夙愿已清 提交于 2019-12-20 07:56:43

问题


What is wrong with this code snippet? i am getting Segmentation fault!

#include<stdio.h>

int main()
{
        struct {
                char* name;
                int age;
        } *emp;
        char* empname = "Kumar";
        int empage = 31;
        emp->name = empname;
        emp->age = empage;
        printf("empname :%s\n",emp->name);
        printf("empage :%d",emp->age);
        return 0;
}

And how to correct this program to work?


回答1:


You are not allocating memory for emp. Before using emp, try

emp = malloc(sizeof(*emp));



回答2:


if you test your code putting in compilation -Wall, the terminal says you that 'emp' is uninitialized therefore you must allocate in dynamic way 'emp' (malloc etc. etc.).

int len_struct = sizeof(*emp);
emp = malloc(len_struct);

PS: This is my advice : i prefer create a struct in global memory (in Data) because i think that this struct you would use in future in the prg.




回答3:


You need not to use pointer to struct nor printf.

#include<stdio.h>
int main()
{
    puts("empname :Kumar");
    puts("empage :30");
    return 0;
}


来源:https://stackoverflow.com/questions/6633916/segmentation-fault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!