0

I am just trying to understand why i get a segmentation fault when I use char *name as the member of the struct name... as apposed to char name[30] as the member, which works properly. thankyou.

struct name
{
    char *name1; // if i make this char name[30]; it works properly
};

void name_prompt(struct name *ptr)
{
    printf("name: ");
    scanf("%s", ptr->name1);
}

int main ()
{
    struct name dylan;
    struct name *ptr = &dylan;

    name_prompt(ptr);

    printf("%s", dylan.name1);

}

2 Answers2

0

char name[30]; actually allocates 30 bytes of space within the struct for reading into. char* name just declares name as a pointer, saying that it could possibly be pointing to allocated space, but not necessarily. You never actually allocate space, so it segfaults.

On a side note, you should use %30s instead of %s for security reasons. (see here)

Aplet123
  • 33,825
  • 1
  • 29
  • 55
0

With a char*, you don't actually have any memory allocated to hold the data you're reading in. You didn't initialize the pointer, so it's pointing to some (semi-)random place, and writing to where it points is undefined behavior, so anything can happen.

If you want it to work with a char*, you'd need to malloc some storage for the pointer to point to (ideally freeing it when you're done), e.g.

int main ()
{
    struct name dylan;

    dylan.name = malloc(50);  // Allocates space for up to 49 characters plus a NUL terminator; limit the scanf to match

    name_prompt(&dylan);

    printf("%s", dylan.name1);

    free(dylan.name); // Release the memory
}

Using the array means the struct itself contains the memory wherever the struct was placed (so the struct is much larger, but doesn't rely on additional memory being allocated to be fully functional), in this case on the stack.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271