Question

Consider,

int main()
{
 char s[10];
 strncpy(s,"hello",5);
 printf("Hello !!%s %d\n",s,strlen(s));
 return 0;
}

When I run this program nothing is printed. But when I comment the call to strncpy, it prints "Hello !! 0".

Used ideone ("http://ideone.com/j1cdKp")

when I used the gcc compiler (Debian 7.4), it gave the expected output ("Hello !!hello 6").

Can anyone explain this behaviour ?

-Newbie

Était-ce utile?

La solution

Part 1

This code causes undefined behavior because you try to print a string s that is uninitialized.

char s[10];
printf("Hello!! %s %d\n",s,strlen(s));

Part 2

This code causes undefined behavior because you try to print a string that is not null terminated. strncpy with the arguments given will copy "hello", but will not copy the trailing null terminator.

char s[10];
strncpy(s,"hello",5);
printf("Hello!! %s %d\n",s,strlen(s));

Part 3

The following code is correct. Note that the argument to strncpy is 6.

char s[10];
strncpy(s,"hello",6);
printf("Hello!! %s %d\n",s,strlen(s));

Autres conseils

Your program causes undefined behaviour. s is uninitalized, and strncpy(s,"hello",5); doesn't copy enough characters to include the null terminator.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top