简体   繁体   中英

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?

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.

  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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM