In my class we are writing our own copy of C’s malloc() function. To test my code (which can currently allocate space fine) I was using:
char* ptr = my_malloc(6*sizeof(char));
memcpy(ptr, "Hello\n", 6*sizeof(char));
printf("%s", ptr);
The output would typically be this:
Hello
Unprintable character
Some debugging figured that my code wasn’t causing this per se, as ptr’s memory is as follows:
[24 bytes of meta info][Number of requested bytes][Padding]
So I figured that printf was reaching into the padding, which is just garbage. So I ran a test of:
printf("%s", "test\nd"); and got:
test
d
Which makes me wonder, when DOES printf(“%s”, char*) stop printing chars?
It stops printing when it reaches a null character (
\0), because%sexpects the string to be null terminated (i.e., it expects the argument to be a C string).The string literal
"test\nd"is null terminated (all string literals are null terminated). Your character arrayptris not, however, because you only copy six characters into the buffer (Hello\n), and you do not copy the seventh character–the null terminator.