简体   繁体   中英

C - malloc and structures, segmentation fault

im trying to make program that stores person's last name and name in a structure that is dynamically allocated and then prints it in terminal. For now i have got "segmentation fault" error after inputing the last name in terminal. How do i make it work? Thanks in advance!

My code:

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

struct person{
        char *last_name;
        char *name;
    };

struct person *p_person;

int main(void)
{
    p_person=malloc(sizeof(struct person));
    scanf("%s", p_person->last_name);
    scanf("%s", p_person->name);


    puts(p_person->last_name);


    free(p_person);
    return 0;
}

p_person->last_name doesn't point to anywhere. You were accessing memory that you are not even permitted to. You invoke undefined behavior accessing it. Solution would be to allocate some memory dynamically or use char last_name[MAXLEN]; in structure.

Solution 1:

struct person{
        char last_name[50];
        char name[50];
    };

Solution 2:

 p_person->last_name = malloc(50);
 if( p_person->last_name == NULL){
     fprintf(stderr,"error in malloc");
     exit(1);
 } 

In the solution-2, You should do the same thing for name also. Free the dynamically allocated memory when you are done working with it.


scanf("%49s", p_person->last_name) One less than the buffer size. When scanf() is finished parsing into a string, it appends NUL terminating character automatically.

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