strlen usually works by counting the characters in a string until a \0 character is found. A canonical implementation would be:

size_t strlen (char *str) {
    size_t len = 0;
    while (*str != '\0') {
        str++;
        len++;
    }
    return len;
}

As for possible inherent bugs in the function, there are none - it works exactly as documented. That's not to say it doesn't have certain problems, to wit:

  • if you pass it a "string" that doesn't have a \0 at the end, you may run into problems but technically, that's not a C string (a) and it's your own fault.
  • you can't put \0 characters within your string but, again, it wouldn't be a C string in that case.
  • it's not the most efficient way - you could store a length up front so you could get the length much quicker.

But none of these are bugs, they're just consequences of a design decision.

On that last bullet point, see also this excellent article by Joel Spolsky where he discusses various string formats and their characteristics, including normal C strings (with a terminator), Pascal strings (with a length) and the combination of the two, null terminated Pascal strings.

Though he has a more, shall we say, "colorful" term for that final type, one which frequently comes to mind whenever I thing of Python's excellent (and totally unrelated) f-strings :-)


(a) A C string is defined as a series of non-terminator characters (any character other than \0) followed by a terminator. Hence this definition disallows both embedded terminators within the sequence, and sequences without such a terminator. Or, putting it more succinctly (as per the ISO C standard):

A string is a contiguous sequence of characters terminated by and including the first null character.

Answer from paxdiablo on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ strlen-function-in-c
strlen() function in c - GeeksforGeeks
May 29, 2023 - The strlen() function in C calculates the length of a given string. The strlen() function is defined in string.h header file.
๐ŸŒ
W3Schools
w3schools.com โ€บ c โ€บ ref_string_strlen.php
C string strlen() Function
C Examples C Real-Life Examples ... it Yourself ยป ยท The strlen() function returns the length of a string, which is the number of characters up to the first null terminating character....
Discussions

c - How does the strlen function work internally? - Stack Overflow
How does strlen() work internally? Are there any inherent bugs in the function? More on stackoverflow.com
๐ŸŒ stackoverflow.com
I recently started coding with C, while using strlen function I get the exact number of length of string and sometimes not....in the below out len should be 3 but it's 4, why?
Because fgets includes the newline character if there was one. More on reddit.com
๐ŸŒ r/cprogramming
10
1
April 30, 2024
string - strlen function in c - Stack Overflow
This might sound a bit dumb but am confused. I know the strlen() would return the size of the character array in c. But there is something different going on with pointers to character. This is my... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Calculating length of a string with strlen()
The first option only works if you have an array of chars, but most of the time (e.g. if you pass the string between functions) you're only going to have a pointer to the chars. The second option always works if your string is properly null terminated. If you want the length of the string including the null terminator itself, you can just do strlen(..) + 1. More on reddit.com
๐ŸŒ r/C_Programming
9
0
July 16, 2024
Top answer
1 of 1
60

strlen usually works by counting the characters in a string until a \0 character is found. A canonical implementation would be:

size_t strlen (char *str) {
    size_t len = 0;
    while (*str != '\0') {
        str++;
        len++;
    }
    return len;
}

As for possible inherent bugs in the function, there are none - it works exactly as documented. That's not to say it doesn't have certain problems, to wit:

  • if you pass it a "string" that doesn't have a \0 at the end, you may run into problems but technically, that's not a C string (a) and it's your own fault.
  • you can't put \0 characters within your string but, again, it wouldn't be a C string in that case.
  • it's not the most efficient way - you could store a length up front so you could get the length much quicker.

But none of these are bugs, they're just consequences of a design decision.

On that last bullet point, see also this excellent article by Joel Spolsky where he discusses various string formats and their characteristics, including normal C strings (with a terminator), Pascal strings (with a length) and the combination of the two, null terminated Pascal strings.

Though he has a more, shall we say, "colorful" term for that final type, one which frequently comes to mind whenever I thing of Python's excellent (and totally unrelated) f-strings :-)


(a) A C string is defined as a series of non-terminator characters (any character other than \0) followed by a terminator. Hence this definition disallows both embedded terminators within the sequence, and sequences without such a terminator. Or, putting it more succinctly (as per the ISO C standard):

A string is a contiguous sequence of characters terminated by and including the first null character.

๐ŸŒ
The Open Group
pubs.opengroup.org โ€บ onlinepubs โ€บ 009604499 โ€บ functions โ€บ strlen.html
strlen
The strlen() function shall return the length of s; no return value shall be reserved to indicate an error. No errors are defined. The following sections are informative. The following example sets the maximum length of key and data by using strlen() to get the lengths of those strings. #include <string.h> ... struct element { char *key; char *data; }; ...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ c_standard_library โ€บ c_function_strlen.htm
C library function - strlen()
The C library strlen() function is used to calculates the length of the string. This function doesn't count the null character '\0'. In this function, we pass the pointer to the first character of the string whose length we want to determine ...
Find elsewhere
Top answer
1 of 6
6

There's a good chance that you're doing this to a string that you have obtained with fgets or a similar input function. In that case, it may well have the newline at the end still.

If you change your code temporarily to:

void xyz (char *number) {
    int i = 0, length = strlen (number);
    while (i < length)
        printf ("Number[%d]: %c (%d)", i, number[i], number[i]);
        i++;
    }
}

that should also show the numeric codes for all characters.

The problem with encoding something like that - 2 in your function is that it will not work with:

xyz ("123");

since it will stop early, printing out only 12. The caller should be calling with valid data, meaning that it should adjust the value to be a numeric string before calling.


You can see this happening in the following program:

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

void xyz (char *number) {
    int i = 0, length = strlen(number) - 2;
    while(i <= length)
    {
        printf("Number[%d]: %c (%d)\n",i, number[i], number[i]);
        i++;
    }
    puts ("===");
}

void xyz2 (char *number) {
    int i = 0, length = strlen(number);
    while(i < length)
    {
        printf("Number[%d]: %c (%d)\n",i, number[i], number[i]);
        i++;
    }
    puts ("===");
}

int main (void) {
    char buff[100];
    printf ("Enter number: ");
    fgets (buff, sizeof (buff), stdin);
    xyz (buff);
    xyz ("12345");
    xyz2 (buff);
    xyz2 ("12345");
    return 0;
}

The (annoted) output of this, if you enter 98765, is:

Enter number: 98765
Number[0]: 9 (57)
Number[1]: 8 (56)
Number[2]: 7 (55)  # Your adjustment works here because of the newline.
Number[3]: 6 (54)
Number[4]: 5 (53)
===
Number[0]: 1 (49)
Number[1]: 2 (50)
Number[2]: 3 (51)  # But not here, since it skips last character.
Number[3]: 4 (52)
===
Number[0]: 9 (57)
Number[1]: 8 (56)
Number[2]: 7 (55)  # Here you can see the newline (code 10).
Number[3]: 6 (54)
Number[4]: 5 (53)
Number[5]:
 (10)
===
Number[0]: 1 (49)
Number[1]: 2 (50)
Number[2]: 3 (51)  # And proper numeric strings work okay.
Number[3]: 4 (52)
Number[4]: 5 (53)
===

If you're looking for a robust user input function that gets around this problem (and avoids dangerous things like unbounded scanf("%s") and gets), I have one elsewhere on SO (right HERE, in fact) drawn from my arsenal.

2 of 6
1

Check if this works for you --

void xyz(char *number)
{
    int length = strlen(number);

    while(i < length)
    {
        printf("Number[]: %c",number[i]);
        i++;
    }
}

and this function, if invoked as

xyz("1234");

should print out:

Number[]: 1
Number[]: 2
Number[]: 3
Number[]: 4

Is that what you really wanted ? If so, then let me point 2 mistakes.

1) "i" is not initialized. It is more a question of good practise. Explicitly initialize your loop control variable (to zero in this case), just don't assume it to be set. 2) your while loop condition with "<=" runs 1 extra cycle that it should.

Remember that arrays start from index '0' (zero), and an array of size 10, has valid index from 0 to 9, and C lang uses null character ('\0'), to terminate a string. So, your "1234" is actually stored as:-

string[0] = '1' string[1] = '2' string[2] = '3' string[3] = '4' string[4] = '\0' (<= NULL)

so if your loop-counter (control variable) i=0 at beginning of loop, for first iteration, you pick string[0], and for 2nd iteration (when i=1) you pick string[1]... and this way, the loop should run only 4 times, i.e. when i==4 (i.e. loopcounter < string-length), you must stop & exit loop.

Hope this clears up your doubt and help. If so, please don't forget to accept the answer.

๐ŸŒ
Reddit
reddit.com โ€บ r/c_programming โ€บ calculating length of a string with strlen()
r/C_Programming on Reddit: Calculating length of a string with strlen()
July 16, 2024 -

Let's say that we have a string char myStr[] = "Hello there!"

The 1st option to calculate the length is

int length = sizeof(myStr)/ sizeof(myStr[0]);

The 2nd option is simply to use the strlen() function, but I'm seeing that it will not count the null terminating character at the end.

My question: Would it be a problem using strlen() in embedded projects since it dosn't include the null terminating character as it's length? Or it's safer to just use the 1st option instead?

I'm thinking as an example of a case when you need to allocate emory, and you're relying on this strlen() function, it will not allocate for the null character, which might lead to problems down the line?

Thanks

๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ c strlen()
C strlen() - Scaler Topics
July 14, 2024 - This article by Scaler Topics discusses the strlen() function defined in string.h header file that calculates the length of the given string or char array excluding the null character in C.
๐ŸŒ
7-Zip Documentation
documentation.help โ€บ C-Cpp-Reference โ€บ strlen.html
strlen - C/C++ Reference Documentation
The strlen() function returns the length of str (determined by the number of characters before null termination).
๐ŸŒ
Vultr
docs.vultr.com โ€บ clang โ€บ standard-library โ€บ string-h โ€บ strlen
C string.h strlen() - Get String Length | Vultr Docs
September 27, 2024 - The strlen() function in C, provided by the string.h library, plays a crucial role in string handling by returning the length of a string. This length is calculated as the number of characters preceding the null terminator (\0), which is used ...
๐ŸŒ
ScriptVerse
scriptverse.academy โ€บ tutorials โ€บ c-program-string-length.html
C Program: Length of a String (w/ strlen()) - ScriptVerse
There already exists a built-in function called strlen() to compute the length of a string, and is available under the <string.h> header library.
๐ŸŒ
Weber State University
icarus.cs.weber.edu โ€บ ~dab โ€บ cs1410 โ€บ textbook โ€บ 8.Strings โ€บ strlen.html
8.2.2.1. strlen
Programmers can implement the counting loop in many ways. Implementing strlen. The strlen function "walks" the C-string from left to right with a loop and counts each character.
๐ŸŒ
Aticleworld
aticleworld.com โ€บ home โ€บ strlen function in c/c++ and implement own strlen()
strlen function in C/C++ and implement own strlen() - Aticleworld
April 18, 2022 - strlen function in C computes length of given string. It takes string as an argument and returns its length and doesnโ€™t count null character.
๐ŸŒ
Hacker News
news.ycombinator.com โ€บ item
The Lobster Programming Language | Hacker News
2 weeks ago - Flow-sensitive type inference with static type checks is, IMHO, a massively underrated niche. Doubly so for being in a compiled language. I find it crazy how Python managed to get so popular when even variable name typos are a runtime error, and how dreadful the performance is ยท All the anonymous ...
๐ŸŒ
Cplusplus
cplusplus.com โ€บ reference โ€บ cstring โ€บ strlen
strlen
function ยท <cstring> size_t strlen ( const char * str ); Get string length ยท Returns the length of the C string str. The length of a C string is determined by the terminating null-character: A C string is as long as the number of characters between the beginning of the string and the terminating ...
๐ŸŒ
W3Resource
w3resource.com โ€บ c-programming โ€บ string โ€บ c-strlen.php
C strlen() function
December 23, 2022 - The strlen() function is used to get the length of a string excluding the ending null character. ... The strlen() function returns the length of str. No return value shall be reserved to indicate an error.
๐ŸŒ
Tutorial Gateway
tutorialgateway.org โ€บ c-program-to-find-length-of-a-string
C Program to Find Length of a String using strlen
April 2, 2025 - The below statement in this program will assign the user entered string to the Str variable. ... We are finding the length of a string using the C strlen function and also assigning the value to the Length variable.