why printf works on non-terminated string

后端 未结 6 1881
渐次进展
渐次进展 2021-01-05 15:47

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

6条回答
  •  再見小時候
    2021-01-05 16:39

    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.

提交回复
热议问题