Strings without a '\0' char?

后端 未结 6 540
醉梦人生
醉梦人生 2020-12-10 18:58

If by mistake,I define a char array with no \\0 as its last character, what happens then?

I\'m asking this because I noticed that if I try to iterate th

6条回答
  •  无人及你
    2020-12-10 19:20

    EDIT (undefined behaviour)

    Accessing array elements outside of the array boundaries is undefined behaviour.
    Calling string functions with anything other than a C string is undefined behaviour.
    Don't do it!

    A C string is a sequence of bytes terminated by and including a '\0' (NUL terminator). All the bytes must belong to the same object.


    Anyway, what you see is a coincidence!

    But it might happen like this

                            ,------------------ garbage
                            | ,---------------- str[cnt] (when cnt == 4, no bounds-checking)
    memory ----> [...|d|o|h|*|0|0|0|4|...]
                      |   |   \_____/  -------- cnt (big-endian, properly 4-byte aligned)
                      \___/  ------------------ str
    

提交回复
热议问题