strlen(3)

C library function

Returns the number of bytes in a C string, not counting the final null byte. How it differs from sizeof, bytes versus characters, the size_t trap.

Synopsis
#include <string.h>
size_t strlen(const char *s);

Description

strlen starts at the address s and counts bytes one by one up to the first '\0', which it does not count. A C string does not store its length anywhere: the only way to know it is to walk through the string, so the cost of strlen grows with the string.

Return value

The number of bytes before the null byte, as a size_t. There is no error value: s must point to a terminated string. Passing NULL, or a char array without a '\0', is undefined behavior, which often ends in a segmentation fault or in reading whatever follows in memory.

Pitfalls

strlen and sizeof do not measure the same thing. For char word[16] = "grademe";, strlen(word) is 7, the text, and sizeof word is 16, the array. On a char *, sizeof gives the size of the pointer, never the size of the text.

strlen counts bytes, not letters. In UTF-8, é takes two bytes, so strlen("café") is 5.

The result is a size_t, an unsigned integer. strlen(a) - strlen(b) can never be negative: when b is longer, the subtraction wraps around and gives a huge number. To compare two lengths, compare them directly with <.

In for (i = 0; i < strlen(s); i++), the condition calls strlen again on every iteration, and each call walks the whole string again. If the compiler does not move that call out of the loop on its own, the running time grows with the square of the length. Compute the length once, before the loop, or test s[i] != '\0'.

After a strncpy(3) that truncated, the destination has no null byte: strlen then keeps going past the end of the array.

Example

length.c
#include <stdio.h>#include <string.h>
int main(void){    char word[16] = "grademe";
    printf("strlen(word) = %zu, sizeof word = %zu\n", strlen(word), sizeof word);    printf("strlen(\"\") = %zu\n", strlen(""));    printf("strlen(\"café\") = %zu\n", strlen("café"));    printf("strlen(\"ab\") - strlen(\"abc\") = %zu\n", strlen("ab") - strlen("abc"));    return 0;}
Terminal
$ gcc -Wall -Wextra length.c -o length$ ./lengthstrlen(word) = 7, sizeof word = 16strlen("") = 0strlen("café") = 5strlen("ab") - strlen("abc") = 18446744073709551615

The last line is 2^64 - 1: 2 - 3 computed as a size_t on a 64-bit machine. Written as a test, if (strlen(a) - strlen(b) > 0), this computation would be true whenever the lengths differ, including when a is the shorter string.

C

strlen

Write gm_strlen, which counts the characters before the terminating null byte without writing anything to the string.

Open the exercise

Now write it yourself.