strlen in C: How strlen Counts Characters & Avoids O(n²) Loops

strlen is the basic operation defined in string.h to measure string length in c, which scans memory from a pointer until it hits the null terminator byte '\0'. strlen in c returns an unsigned size_t value for the number of characters up to the null character (not the number of characters in the array, which is sizeof), and on an uninitialized char array or a buffer that doesn't contain a null terminator, it reads past the array bounds and invokes undefined behaviour. Also, do not use strlen in C in the for loop condition, since this can make the single pass O(n) into a bottleneck on long strings of O(n^2).

strlen in C: String Length vs sizeof, Null Terminators & Complexity — Technical Overview

strlen is the basic operation defined in string.h to measure string length in c, which scans memory from a pointer until it hits the null terminator byte '\0'. strlen in c returns an unsigned size_t value for the number of characters up to the null character (not the number of characters in the array, which is sizeof), and on an uninitialized char array or a buffer that doesn't contain a null terminator, it reads past the array bounds and invokes undefined behaviour. Also, do not use strlen in C in the for loop condition, since this can make the single pass O(n) into a bottleneck on long strings of O(n^2).

#include <stdio.h>
#include <string.h>

int main(void) {
    char msg[32] = "C17 Systems";
    printf("strlen(msg) = %zu, sizeof(msg) = %zu\n", strlen(msg), sizeof(msg));
    return 0;
}

Runnable C example

#include <stdio.h>
#include <string.h>

int main(void) {
    char msg[32] = "C17 Systems";
    printf("strlen(msg) = %zu, sizeof(msg) = %zu\n", strlen(msg), sizeof(msg));
    return 0;
}

Open example in compiler

Expected Output

strlen(msg) = 11, sizeof(msg) = 32