Strlen Function behavior on single character

馋奶兔 提交于 2019-12-23 23:08:08

问题


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?


回答1:


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.




回答2:


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:


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.



来源:https://stackoverflow.com/questions/35477662/strlen-function-behavior-on-single-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!