#include
#include
#include
int main(void)
{
char qq[] = {\'a\' , \'b\' , \'c\' , \'d\'};
char qqq[] = \"abcd\";
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.
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'};
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.
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.