Reputation: 128
I just run this code and what i get for n=1 is not what i expect to get. Can you explain why is this happening?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXRIGA 11
int main()
{
char s[MAXRIGA+2];
char a[MAXRIGA]="pippo";
strncpy(s, a, 1); // n=1
printf("%s", s);
return 0;
}
returns
pF
instead if n=2 or more i get what i want.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXRIGA 11
int main()
{
char s[MAXRIGA+2];
char a[MAXRIGA]="pippo";
strncpy(s, a, 2); // n=2
printf("%s", s);
return 0;
}
returns
pi
Upvotes: 2
Views: 546
Reputation: 7020
Since you are not initializing the array s
it contains random values. Strings in C are terminated by a NULL character, so when you initialize the array a
with "pippo" the values it contains are:
offset | 0 | 1 | 2 | 3 | 4 | 5 |
value | p | i | p | p | o | \0 |
When you call printf
it needs to decide where the end of the string is and it does this by printing characters until it gets to the terminating NULL. If s
contains random data and you only copy in a single character then printf
will print the string until it gets to a byte that happens to be NULL. In this case, it looks like the 3rd byte of the random data was \0 so printf prints characters up to that point.
Upvotes: 3
Reputation: 2556
strncpy
does not append the null terminator onto strings. You need to manually add it after using strncpy
.
Like this:
strncpy(s, a, 1); // n=1
s[1]=0;
printf("%s", s);
The F (from pF) is simply any arbitrary character that still happens to reside in the position in memory encountered before any null terminator is found. Strictly speaking your code should produce Buffer overrun error, or Access violation error.
Add the null terminator after using strncpy
and your problem will disappear :)
Upvotes: 5
Reputation: 18299
From man strncpy
:
The strncpy() function is similar, except that at most n bytes of src are copied. Warning: If there is no null byte among the first n bytes of src, the string placed in dest will not be null-terminated.
You are copying only one byte from the source string, which is not a null-terminator. So you get an undefined behavior here, as trying to print a non-terminated string. The same for n=2
, which appears to work by accident.
Upvotes: 9