Here is my code:
void func(char c)
{
char * ptr = &c;
size_t len = strlen(ptr);
printf("len - %d\n", len);
}
len is always printed as 1.
strlen(..) determines the length of a char array by finding the null character (\0) at the end of it. Here ptr is initialized with just the address of a single character (c). c does not contain any null characters. How does ptr get the length?
You cannot use strlen() on a pointer that does not point to a null-terminated array. It invokes undefined behavior.
Once your program hits UB, nothing is guaranteed.
FWIW, strlen() returns a type size_t, so you should use %zu format specifier to print the result.
The behaviour of your code is undefined on two counts. It returns 1 by accident.
strlen works by starting at a given address, and incrementing that address until \0 is reached. This is consistent with how the C standard library models strings. If you don't own all the memory (as a contiguous block) between the starting address and that \0 then the input to strlen is malformed.
The behaviour of printf is undefined due to an incorrect format specifier. Use %zu for size_t.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With