Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying strings in C

Tags:

c

string

I'm learning about strings in c. I am using code::blocks as a compiler, even though it's not just for c. So, the problem with the code below is that the output for string2 is the stored 5 characters plus string1's output. I'll show you:

#include <stdio.h>
#include <string.h>          /* make strncpy() available */

int main()
{
char string1[]= "To be or not to be?";
char string2[6];

/* copy first 5 characters in string1 to string2 */
strncpy (string2, string1, 5);

printf("1st string: %s\n", string1);
printf("2nd string: %s\n", string2);
return 0;
}

Output is:

1st string contains: To be or not to be? 
2nd string contains: To be To be or not to be?

If you ask me, that's a lot more than 5 characters...

like image 639
Michael O'hearn Avatar asked Aug 31 '26 23:08

Michael O'hearn


2 Answers

From the strncpy man page:

No null-character is implicitly appended to the end of destination, so destination will only be null-terminated if the length of the C string in source is less than num.

Since the original string is greater in length than 5, no NULL is being added.

As others have pointed out, to add some safety to it:

strncpy (string2, string1, sizeof(string2));
string2[sizeof(string2)-1] = '\0';

Note that if string2 is obtained through a malloc():

char * string2 = malloc(123); //sizeof(string2) == sizeof(void *) and not 123

And the above code would fail.

For the sake of completeness, here is the code: http://ideone.com/eP4vd

like image 107
Vinicius Kamakura Avatar answered Sep 03 '26 14:09

Vinicius Kamakura


You are not terminating string2 with '\0', so the printf overruns. Try to do:

memset(string2,0,6);

before using string2. or, since you know you are copying 5 chars, after strncpy:

string2[5] ='\0';

so you properly terminate correctly the string.

pay attention to the fact that you should put '\0' after exactly the number of characters you did copy, otherwise you will see garbage even in the middle of the string.

like image 32
Felice Pollano Avatar answered Sep 03 '26 15:09

Felice Pollano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!