Search code examples
cstringstructure

segmentation fault while assigning string to a struct variable in C


I am currently learning structures in C and struggling with string assignment.

I get segmentation fault if I write my code like this:

#include<stdio.h>

int main(void)
{
    struct part {
        char *name;
    };
    
    struct part part_1[2];
    
    fgets(part_1[0].name,20,stdin); 

    printf("%s\n",part_1[0].name);  
}   

I try some other ways and things are OK, so I don't get what's wrong with the above code.

For example: If I change fgets(part_1[0].name,20,stdin) into part_1[0].name = "some_dummy_data_here", I don't get fault.

And the most confusing thing is if I do fgets(part_1[1].name,20,stdin) instead of fgets(part_1[0].name,20,stdin), it works.

However, if I use array instead of pointer, I meet no problem. For example, if I write code like this:

struct part{
    char name[20];
}

everything runs smoothly.

So, what is the problem here?


Solution

  • The difference between char * name and char name [20] is that when the latter is defined, the compiler has allocated memory space for it. If you want to use pointers, you need to allocate memory for them in advance. For example, use the malloc function:

    part_1[0].name = malloc(sizeof(char)*20)

    and then fgets won't generate segmentfault.

    As for the code part_1[0].name = "some_dummy_data_here", the string "some_dummy_data_here" is a string constant and has already been in memory. This code let the pointer name point to it so there is no need to allocate space in advance.