而使用malloc与字符指针分割故障 [英] Segmentation fault while using malloc with char pointers

查看:103
本文介绍了而使用malloc与字符指针分割故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的C和学习结构。我试图的malloc A字符指针大小为30,但它给分段错误(核心转储)。我搜索它上网和放大器上; SO,但我不能够解决这个问题。任何帮助将大大AP preciated。结果
也许我访问结构的的char * 成员不正确?

  typedef结构{
INT X;
诠释Ÿ;
字符* F;
字符*升;
}海峡;无效create_mall();无效create_mall()// malloc的结构体
{
STR * P;
P-> F =(字符*)malloc的(的sizeof(char)的* 30); //此处分段故障
P-→1 =(字符*)malloc的(的sizeof(char)的* 30);
的printf(请输入用户ID);
scanf函数(%d个,&安培; P-> X);
的printf(\\ n输入电话号码:);
scanf函数(%d个,&安培; P-> Y);
的printf(\\ n输入的第一个名字:);
scanf的(%-29,对 - &F)的温度;
的printf(\\ n输入姓氏:);
scanf的(%-29,对 - →1);
的printf(\\ nEntered值是:%D%s%S \\ n,P-> X,P-GT&; Y,P-GT&; F,P-→1)​​;
}INT主要(无效)
{
create_mall();
返回0;
}


解决方案

下面是你的问题:

  STR * P;

您已经声明一个指向 STR 的实例,但是你有没有用值初始化它。你要么需要这个变量移动到堆栈:

 海峡磷;

...或的malloc 一些内存为它第一次:

 海峡* P =(STR *)malloc的(的sizeof(STR));

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("\nEnter the phone number:");
scanf("%d",&p->y);
printf("\nEnter the First name:");
scanf("%29s",p->f);
printf("\nEnter the Last name:");
scanf("%29s",p->l);
printf("\nEntered values are: %d %d %s %s\n",p->x,p->y,p->f,p->l);
}

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

解决方案

Here's your problem:

str *p;

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;

...or malloc some memory for it first:

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

这篇关于而使用malloc与字符指针分割故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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