Search code examples
cstring-length

Why the strlen() function doesn't return the correct length for a hex string?


I have a hex string for example \xF5\x17\x30\x91\x00\xA1\xC9\x00\xDF\xFF, when trying to use strlen() function to get the length of that hex string it returns 4!

const char string_[] = { "\xF5\x17\x30\x91\x00\xA1\xC9\x00\xDF\xFF" };
unsigned int string_length = strlen(string_);
printf("%d", string_length); // the result: 4

Is the strlen() function dealing with that hex as a string, or is something unclear to me?


Solution

  • For string functions in the C standard library, a character with value zero, also called a null character, marks the end of a string. Your string contains \x00, which designates a null character, so the string ends there. There are four non-null characters before it, so strlen returns four.

    C 2018 7.1.1 1 says:

    A string is a contiguous sequence of characters terminated by and including the first null character… The length of a string is the number of bytes preceding the null character…

    C 2018 7.24.6.3 2 says:

    The strlen function computes the length of the string pointed to by s [its first argument].

    You could compute the size of your array as sizeof string_ (because it is an array of char) or sizeof string_ / sizeof *string_ (to compute the number of elements regardless of type), but this will include a terminating null character because defining an array with [] and letting the length be computed from a string literal initializer includes the terminating null character of the string literal. You may need to hard-code the length of the array, possibly using #define to define a preprocessor macro, and use that length in the array definition and in other places where the length is needed.