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

有帮助吗?

解决方案

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));

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top