Understanding strlen() Internally by Writing It From Scratch in C

Published: (February 6, 2026 at 02:04 AM EST)
2 min read
Source: Dev.to

Source: Dev.to

Introduction

strlen() is a predefined function used to determine the length of a given string.

Syntax

size_t strlen(const char *str);

Example

char str[6] = "hello";
size_t len = strlen(str);   // len = 5

What Is a String in C?

In C, a string is not a distinct data type. It is an array of characters terminated by a null character ('\0'). The null character indicates the end of the string.

Header File

strlen() is declared in the <string.h> header file, which contains many standard library function declarations.

Implementing strlen() from Scratch

Prototype

int my_strlen(const char *str);
  • const char *str – a pointer to the first character of the string (the base address).
  • const prevents modification of the string inside the function, helping avoid bugs.

Implementation

int my_strlen(const char *str)
{
    int cnt = 0;
    while (str[cnt] != '\0')
    {
        cnt++;
    }
    return cnt;
}

How It Works – Step by Step

  1. Argument Passing – The base address of the string is passed to the function.
  2. Counter Initializationcnt is set to 0 and will count the characters.
  3. Loop Condition – The loop continues while str[cnt] is not the null character '\0'.
  4. Pointer Arithmetic – Although we use str[cnt], the compiler treats it as pointer arithmetic (*(str + cnt)).
  5. Incrementing the Counter – Each iteration moves to the next character and increments cnt.
  6. Loop Termination – When str[cnt] equals '\0', the condition becomes false, the loop ends, and cnt holds the length of the string (excluding the null terminator).

Memory Representation

+---+---+---+---+---+---+
| h | e | l | l | o | \0|
+---+---+---+---+---+---+
  ^               ^
  |               |
 base address   null terminator

Why It Returns the Length of the String

  • Every character before the null terminator is counted.
  • The null character itself is not counted.
  • Counting stops exactly at the end of the string, giving the true length.

Final Understanding

By writing strlen() from scratch, you can see:

  • How strings are stored in memory as a sequence of characters ending with '\0'.
  • The importance of the null character in marking the end of a string.
  • How pointer arithmetic and simple loops are used for string traversal in C.
Back to Blog

Related posts

Read more »

C Isn't a Language

Article URL: https://faultlore.com/blah/c-isnt-a-language/ Comments URL: https://news.ycombinator.com/item?id=46907350 Points: 10 Comments: 10...

Fighting with json - a war story

!Cover image for Fighting with json - a war storyhttps://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-...