简体   繁体   English

总线错误:10 在结构指针 C 上使用 malloc

[英]Bus error: 10 using malloc on struct pointer, C

I'm trying to malloc some memory for a struct pointer.我正在尝试将 malloc 一些 memory 用于结构指针。 The code compiles fine, but when I run it I get bus error: 10 after the user enters their name.代码编译得很好,但是当我运行它时,我得到总线错误:用户输入他们的名字后 10 。 I'm not sure what I'm doing wrong so would appreciate any help!我不确定我做错了什么,所以会很感激任何帮助!

Thanks in advance:)提前致谢:)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main(){

    struct name{
        char *first;
        char *last;
    };

    struct name *user;

    char temp[10];

    printf("What is your first name?\n");
    scanf("%s", temp);
    user->first = (char*) malloc(strlen(temp)+1);
    strcpy(user->first, temp);

    printf("What is your last name?\n");
    scanf("%s", temp);
    user->last = (char*) malloc(strlen(temp)+1);
    strcpy(user->last, temp);

    printf("Your name is %s %s\n", user->first, user->last);

    free(user->first);
    free(user->last);

    user->first = NULL;
    user->last = NULL;

}

You didn't allocate memory for user to point to.您没有分配 memory 供user指向。 So it is left uninitialized and attempting to dereference that pointer leads to undefined behavior .所以它未初始化并试图取消引用该指针会导致未定义的行为

You need to allocate memory for user , just as you did for its fields:您需要为user分配 memory ,就像您为其字段所做的那样:

struct name *user = malloc(sizeof *user);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM