what should strlen() really return in this code?

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


        
相关标签:
4条回答
  • 2021-01-21 13:59

    In your code

      char qq[] = {'a' , 'b' , 'c' , 'd'};
    

    qq is not qualified to be called a string, as it is not null-terminated. So calling strlen() wilh qq is inviting trouble.

    What actually happens here is, strlen() goes past the last valid element in qq in search of terminating null (which is actually missing), and thus, venture into out-of-bound memory, which invokes undefined behaviour.

    Solution: To make qq a string, you have to add the null-terminator in the initializer list yourself, like

     char qq[] = {'a' , 'b' , 'c' , 'd', '\0'};
    

    That said, as I already mentioned in my comment, as strlen() return type is size_t, you should use %zu format specifier to print the result.


    Just in a lighter mood, to answer

    what should strlen() really return in this code?

    If I say, "The phone number of the Respected President of India", well, technically, I might be correct !!

    On a serious note, the output of UB in, well, undefined.

    0 讨论(0)
  • 2021-01-21 13:59

    strlen() computes length of string but char qq[] = {'a' , 'b' , 'c' , 'd'}; is not string. Undefined results are obtained when 'Non-String' data is passed to strlen.

    Strings are null terminated in c.

    It should be char qq[] = {'a' , 'b' , 'c' , 'd','\0'};

    0 讨论(0)
  • 2021-01-21 14:10

    Your string is not null-terminated. That means your code is not deterministic. strlen() will terminate whenever it encounters a \0 (null byte/character); the result can vary due to it sequential scanning until the \0 is encountered.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题