Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strlen Function behavior on single character

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?

like image 921
viv Avatar asked Feb 06 '26 16:02

viv


2 Answers

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.

like image 118
Sourav Ghosh Avatar answered Feb 09 '26 06:02

Sourav Ghosh


The behaviour of your code is undefined on two counts. It returns 1 by accident.

  1. 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.

  2. The behaviour of printf is undefined due to an incorrect format specifier. Use %zu for size_t.

like image 29
Bathsheba Avatar answered Feb 09 '26 05:02

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!