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