Strlen Function behavior on single character

2019-07-13 17:57发布

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?

3条回答
在下西门庆
2楼-- · 2019-07-13 18:38

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.

查看更多
聊天终结者
3楼-- · 2019-07-13 18:40

c does not contain any null characters. How does ptr get the length?

It doesn't. It appears to give the correct answer in your tests because the memory location following the address of c happens to contain a zero byte. This location is not defined to contain a zero, nor is the program allowed to access it, so you cannot count on such code continuing to work.

In the language of the C standard, the behavior of the program is undefined, which means that not only is the result of the operation unpredictable, the entire program is rendered meaningless.

Even without taking into account undefined behavior, the above code can stop working with the slightest change - for example, when you change architecture, compiler, or even compilation flags, or when you add more functions into the mix. While such code snippets can be useful to learn how stuff works under the hood, they should never be used in production code.

查看更多
Animai°情兽
4楼-- · 2019-07-13 18:58

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.

查看更多
登录 后发表回答