开发者

Segmentation fault [duplicate]

This question already has answers here: Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer (5 answers) Closed 6 years ago.

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

#include<stdio.h>

int main()
{
        struct {
                char* 开发者_Python百科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?


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

emp = malloc(sizeof(*emp));


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.


You need not to use pointer to struct nor printf.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜