I found a very interesting question.
When I’m using following code:
int main() {
char * in = "hi, ";
char str[10];
strncpy(str, in, 2);
printf("output = %s", str);
return 0;
}
My result is nothing, the printf didn’t work.
But if I use this:
int main() {
char * in = "hi, ";
char * str = malloc(sizeof(char) * 10) ;
strncpy(str, in, 2);
printf("output = %s", str);
return 0;
}
I can get what I expect.
Why does this happen? Is it because of stack and heap? How exactly does that makes this huge difference?
The code compiles fine. The run-time error could be because, you haven’t terminated the
strwith null.From the man page:
Add
str[2]=0;after thestrncpy().