使用带有char指针的malloc时出现分段错误

Vbp*_*Vbp 2 c malloc pointers char segmentation-fault

我是C的新手并且学习结构.我正在尝试malloc使用大小为30的char指针,但它会产生分段错误(核心转储).我在互联网上搜索了它,但是我无法解决这个问题.任何帮助都感激不尽.
可能我char*错误地访问了struct 的成员?

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;
}
Run Code Online (Sandbox Code Playgroud)

Ada*_*ras 8

这是你的问题:

str *p;
Run Code Online (Sandbox Code Playgroud)

您已声明指向实例的指针str,但尚未使用值初始化它.您需要将此变量移动到堆栈:

str p;
Run Code Online (Sandbox Code Playgroud)

......或malloc先为它记忆一下:

str *p = (str*)malloc(sizeof(str));
Run Code Online (Sandbox Code Playgroud)

  • 非常请,不建议初学者投出malloc()的返回值! (2认同)

Chr*_*ton 5

您从来没有为结构本身分配空间,而只是为它分配了指针。

尝试类似:

str *p = malloc(sizeof(str));
Run Code Online (Sandbox Code Playgroud)

  • +1是*没有*强制转换malloc()结果的唯一答案。 (2认同)
  • @mux [这就是原因。](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) (2认同)