Protecting the world

from criminally bad code

strlen

synopsis

#include <string.h>

size_t strlen(const char* s);

Description

The strlen measures the length of a null-terminated string.

Pitfalls

The reported length does not include the terminator

A common error when using strlen is to assume that the reported length includes the terminating null character. It does not, so it is necessary to add one if that is the value wanted.

The reported length takes no account of multi-byte character encodings

The length returned by strlen is measured in bytes, not characters. This is an important distinction when using a multi-byte character encoding such as UTF-8.

This is not to say that the use of strlen is always wrong under those circumstances: if the requirement is to measure the amount of memory occupied by the string then strlen is a perfectly reasonable way to obtain that information. However, any processing that interprets the string as a sequence of characters should take account of the character encoding, and if the encoding uses anything other than a fixed one byte per character then strlen will not give the appropriate result.

Portability

  •  C90
  •  C99
  •  C++98
  •  C++11

In C++, use of the header <string.h> is deprecated in favour of <cstring>.

Further reading

  • The strlen function, Programming languages — C, ISO/IEC 9899:1999, §7.21.6.3, p333
  • strlen, The Open Group Base Specifications, Issue 7, The Open Group, 2008
  • strlen(3), Linux Programmer’s Manual, The Linux man-pages project
  • String Length, The GNU C Library Reference Manual, The GNU Project