#Copying a char* into a pointer to an char[] in a header file

30 messages · Page 1 of 1 (latest)

quasi epoch
#

Hello, I am currently stuck trying to figure out why strncpy(user->name, username, sizeof(username)); gives me a segfault. user comes from:

    char name[64];
    ...```
and username:
```char *username = argv[1];```
the first line of code above is the one giving me a segfault, and I do not know why, everything I have read tells me that it should work.
waxen urchinBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

lusty shadow
#

sizeof(username) is the size of a pointer to character

#

aside from that, i don't think strncpy is what you want here

quasi epoch
#

what would you use?

lusty shadow
#

strcpy + a length check

quasi epoch
#

a length check?

lusty shadow
#

something like

if(strlen(argv[1])>=sizeof(user->name)){
    /*name is too long to fit into your buffer, exit now with an error message of your choosing*/
}
strcpy(user->name,argv[1]);
quasi epoch
#

so like user->name[10] = '\0';
?

#

I see

#

I will try that, thank you

#

still givin me segfualt sadly :/

lusty shadow
#

did you actually initialize user to something meaningful?

quasi epoch
#

wdym?

lusty shadow
#

user is a pointer, so it ought to point at something for you to use it

quasi epoch
#

wait give me a sec

lusty shadow
#

and do you also provide an argument for argv[1]

quasi epoch
#

okay so I do not initialize it to something meaningful as you put it, i just did struct user_t *user

#

and yes i did

#

but why would what I initialize user to matter?

lusty shadow
#

user is just a pointer to some user_t

quasi epoch
#

yes

lusty shadow
#

it doesn't provide any store for the user_t itself

quasi epoch
#

wait

#

😐

lusty shadow
#

you will probably be fine without a pointer and just making user of type user_t

quasi epoch
#

🫥

#

welp

#

thank you

#

!solved