strlen, strnlen_s

< c‎ | string‎ | byte
Defined in header <string.h>
size_t strlen( const char *str );
size_t strnlen_s( const char *str, size_t strsz );
(2) (since C11)
1) Returns the length of the given byte string, that is, the number of characters in a character array whose first element is pointed to by str up to and not including the first null character. The behavior is undefined if there is no null character in the character array pointed to by str.
2) Same as (1), except that the function returns zero if str is a null pointer and returns strsz if the null character was not found in the first strsz bytes of str.
As with all bounds-checked functions, strnlen_s is only guaranteed to be available if __STDC_LIB_EXT1__ is defined by the implementation and if the user defines __STDC_WANT_LIB_EXT1__ to the integer constant 1 before including string.h.


[edit] Parameters

str - pointer to the null-terminated byte string to be examined
strsz - maximum number of characters to examine

[edit] Return value

1) The length of the null-terminated string str.
2) The length of the null-terminated string str on success, zero if str is a null pointer, strsz if the null character was not found.

[edit] Notes

strnlen_s and wcsnlen_s are the only bounds-checked functions that do not invoke the runtime constraints handler. They are pure utility functions used to provide limited support for non-null terminated strings.

[edit] Example

#include <string.h>
#include <stdio.h>
int main(void)
    const char str[] = "How many characters does this string contain?";
    printf("without null character: %zu\n", strlen(str));
    printf("with null character: %zu\n", sizeof str);


without null character: 45
with null character: 46

[edit] References

  • C11 standard (ISO/IEC 9899:2011):
  • The strlen function (p: 372)
  • K. The strnlen_s function (p: 623)
  • C99 standard (ISO/IEC 9899:1999):
  • The strlen function (p: 334)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • The strlen function

[edit] See also

returns the length of a wide string
(function) [edit]
returns the number of bytes in the next multibyte character
(function) [edit]