Link to home
Start Free TrialLog in
Avatar of Adrenaline
Adrenaline

asked on

strncpy question

i am using strncpy to copy a string over to a field called ll->ldata.string. Below is the code snippet. The results are as follows: My question is why is it after copying final into ll->ldata.string the characters "10" became "104"????

thanks

name is :descp  size is 2
len: 0   ll->ldata.string:
len: 2   final: 10
name is :descp  size is 2
len: 3   ll->ll->ldata.string: 104

memset (ll->ldata.string, 0, ll->lfield.size);
 
printf("name is :%s\t size is %d\n",ll->lfield.name, ll->lfield.size);
printf("len: %d\t ll->ldata.string: %s\n", strlen(ll->ldata.string), ll->ldata.string);
printf("len: %d\t final: %s\n", strlen(final), final);
strncpy (ll->ldata.string, final, ll->lfield.size);
printf("name is :%s\t size is %d\n",ll->lfield.name, ll->lfield.size);
printf("len: %d\t ll->ldata.string: %s\n", strlen(ll->ldata.string), ll->ldata.string);

Open in new window

Avatar of Jaime Olivares
Jaime Olivares
Flag of Peru image

you have to be aware of this:
C strings are null terminated, most C standard library that handle strings, like strcpy() and strcat() puts automatically a null character when processing a string.
But strncpy DOES NOT put a null character after string when the size of the copied string is equal or exceeds the specified size. So, if you don't handle this situation, you will see some unexpected characters after the string because it is not properly terminated by a null character.
Avatar of Infinity08
Or in other words :

       strncpy (ll->ldata.string, final, strlen(final) + 1);

Note the + 1 for the trailing '\0' character.
ASKER CERTIFIED SOLUTION
Avatar of Jaime Olivares
Jaime Olivares
Flag of Peru image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
May I ask what the reason for the B grade is ? That usually means that something was missing in our answers. If so, you can always ask for clarification before accepting an answer ...

Also note that what evilrix suggested is slightly different than what jaime_olivares (and me) suggested. It assumes there is no NULL at the end of the source string ... Is that the case ???