将 malloc 与 char 指针一起使用时出现分段错误 [英] Segmentation fault while using malloc with char pointers

查看:33
本文介绍了将 malloc 与 char 指针一起使用时出现分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 C 和学习结构的新手.我正在尝试 malloc 一个大小为 30 的 char 指针,但它给出了分段错误(核心转储).我在互联网上搜索了它&所以但我无法解决这个问题.任何帮助将不胜感激.
可能我错误地访问了结构的 char* 成员?

I am new to C and learning structs. I am trying to malloc a char pointer with size 30 but it is giving a segmentation fault(core dump). I searched it on the internet & SO but am not able to resolve this. Any help will be much appreciated.
Probably I am accessing the char* member of the struct incorrectly ?

typedef struct{
int x;
int y;
char *f;
char *l;
}str;

void create_mall();

void create_mall() //Malloc the struct
{
str *p;
p->f = (char*)malloc(sizeof(char)*30);  // segmentation fault here
p->l = (char*)malloc(sizeof(char)*30);
printf("Enter the user ID:");
scanf("%d",&p->x);
printf("
Enter the phone number:");
scanf("%d",&p->y);
printf("
Enter the First name:");
scanf("%29s",p->f);
printf("
Enter the Last name:");
scanf("%29s",p->l);
printf("
Entered values are: %d %d %s %s
",p->x,p->y,p->f,p->l);
}

int main(void)
{
create_mall();
return 0;
}

推荐答案

这是你的问题:

str *p;

您已经声明了一个指向 str 实例的指针,但您还没有使用值对其进行初始化.您要么需要将此变量移动到堆栈中:

You've declared a pointer to an instance of str, but you haven't initialized it with a value. You either need to move this variable to the stack:

str p;

...或 malloc 先给它一些内存:

...or malloc some memory for it first:

str *p = (str*)malloc(sizeof(str));

这篇关于将 malloc 与 char 指针一起使用时出现分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆