what should strlen() really return in this code?

后端 未结 4 1203
南旧
南旧 2021-01-21 13:34
#include 
#include 
#include 
int main(void)
{
    char qq[] = {\'a\' , \'b\' , \'c\' , \'d\'};
    char qqq[] = \"abcd\";         


        
4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-21 14:17

    strlen will work its way forward until it finds a \0 character, counting how many characters there are along the way.

    Because qq does not have a \0 in it, strlen will keep going into other, unrelated memory. Eventually, by chance, it encounters a \0 byte.

    Apparently for you that is after 15 bytes (or 11 bytes beyond the end of qq).
    But it is not deterministic or guaranteed, and is very unsafe.
    It is very possible that strlen will end up trying to read invalid memory before it happens to find a \0 character, in which case your program will seg-fault.

提交回复
热议问题