DEV Community

hassaan-syed
hassaan-syed

Posted on

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

Let us understand the internal concept of strlen().

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

Syntax of strlen:
strlen(variable_name);

Example:
char str[6] = "hello"; // here length = 5

char str[6] = "hello";
strlen(str);   // Output: 5

Enter fullscreen mode Exit fullscreen mode

strlen(str);

Firstly, what is a string?

In C, a string is not a data type.
A string is a collection of characters which always ends with a special character '\0', also known as the null character.

This null character indicates the end of the string.
It does not mean “nothing in memory”, but it tells functions where the string stops.

Header file information:

There are some library files which include many function declarations to perform different tasks.
Here, we are learning about the strlen() function, which comes under the <string.h> header file.

Let us start from scratch — how strlen() works internally.

Prototype of strlen:

int my_strlen(const char *str);
Enter fullscreen mode Exit fullscreen mode

Explanation:
int → return type (returns length of string)
my_strlen → function name
const char *str →

  • char * is a character pointer which stores the base address of the string
  • const is used so that the value of the string cannot be modified inside the function (this helps avoid bugs)
  • str is the variable name (kept meaningful and relatable)

code:

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

Enter fullscreen mode Exit fullscreen mode

We use a pointer to traverse the string from one character to another while counting.

How this works step by step:

When we pass the argument:
my_strlen(str);

The base address of the string is passed to the function.

Counter initialization:

Here, cnt is an integer variable used to count the number of characters in the string.

While loop condition:

We know that every string ends with the null character '\0'.
So the loop runs until '\0' is encountered.

Although we are using str[cnt], internally this works using pointer arithmetic.

Incrementing the counter:

Each increment moves to the next character of the string and increases the count.

Memory Representation:

Loop termination:

When str[cnt] becomes '\0':

  • The condition becomes false
  • The while loop terminates
  • The function returns the value of cnt

THIS IS MY MY_STRING.H(project)
Full code on GitHub: my_string.h

Why does it return the length of the string?

Because:

  • Every character is counted
  • The null character '\0' is not counted
  • Counting stops exactly at the end of the string

Final understanding:

By writing strlen() from scratch, I understood:

  • How strings are stored in memory
  • Why the null character is important
  • How string traversal works internally in C

Top comments (0)