简体   繁体   中英

Bus error: 10 using malloc on struct pointer, C

I'm trying to malloc some memory for a struct pointer. The code compiles fine, but when I run it I get bus error: 10 after the user enters their name. 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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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