I am wondering how does printf() figure out when to stop printing a string, even I haven\'t put a termination character at the end of the string? I did an experiment by mall
Is because you had bad lucky and the next byte of your malloc
'ed string was a 0
byte.
You can confirm that by doing:
const char* digits = "0123456789";
char* buff = (char*)malloc(10);
memcpy(buff, digits, 10);
printf("%s, %d\n", buff, (int)*(buff + 10));
Your program have to print:
0123456789 0
And that 0 is the NULL which you did't malloc'ed but it was there. Note that this behavior is UNDEFINED so you cannot trust in these things. As I said before this happened because you are unlucky! The good thing to happen in this situation is a SIGSEGV.