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 problem - in both cases - is that your string won't be properly terminated after your call to strncpy
.
You specify that 2
characters are copied, and your source string in
has a length of 4. So strncpy
will copy 2 characters, and since that is less than the length of the source string no null terminator will be added - to understand why this is so, review the docs for strncpy:
If count is reached before the entire string src was copied, the resulting character array is not null-terminated.
In this case you'll want:
str[2] = '\0';
after the 'strncpy'.
The second case may seem to work because the buffer that you get from malloc
happens to be initialized to all zeros, but you shouldn't rely on this.
Please review the docs for strncpy, noting the exception for null termination, and in general, be careful with string termination!
For even more detail see: Why are strings in C++ usually terminated with '\0'?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With