What is strlen in Embedded C- Best C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

strlen in Embedded C

Chapter 9, Lecture 9 of the free C programming course: string length, sizeof, size_t and your own strlen

9.3.1
Chapter section
Lecture 9
Free C tutorial
Beginner
Level

strlen in C is the first string library function every programmer meets, and the one most often misunderstood. It does not return the size of the array and it does not count the terminator; it walks the text and counts characters until it meets '\0'. In this lecture of our free C programming course you will see exactly how it works, write two versions of it yourself, and learn the traps that matter in embedded C programming.

This free C tutorial uses only standard C, compiled with gcc -std=c17 -Wall -Wextra. The programs are original and small enough to type by hand, which is the best way to learn.

What You Will Learn

  • What strlen() returns and why it excludes the terminator
  • The difference between strlen() and sizeof
  • How to write your own length function with an index and with pointer subtraction
  • Why while (*s) is a valid loop condition
  • The unsigned-arithmetic trap caused by size_t
  • Why calling strlen inside a loop condition is slow, and how it can run away on unterminated data in firmware

Prerequisites

Know what a character array is, what the null terminator does, and how a pointer walks through an array. Lecture 8 of this free embedded C course covered how strings get into memory; here we measure them.

What strlen in C Actually Returns

The prototype lives in <string.h>: size_t strlen(const char *s);. It takes the address of the first character, counts characters one by one, and stops the moment it sees a byte whose value is zero. The zero is not counted. So strlen("UART2") is 5, even though five letters plus a terminator occupy six bytes of storage.

The array that holds the text can be much larger than the text itself. The diagram shows a 16-byte buffer holding the word UART2. Only the blue cells before the terminator are counted; everything after the terminator is spare room that strlen never looks at.

buf[16] = “UART2” and what strlen sees
index01234567
valueUART2\000
strlencounts 5 cells, stops at the first terminator

Return type matters

strlen returns size_t, an unsigned type. Print it with %zu, not %d. Using the wrong specifier is undefined behaviour and warns under -Wall.

strlen in C vs sizeof: Two Different Questions

Beginners mix these up because both produce a number. They answer different questions. sizeof is a compile-time operator that reports how many bytes an object occupies. strlen is a run-time function that reports how many characters come before a terminator.

ExpressionMeaningFor char buf[16] = "UART2"For const char *msg = "firmware"
sizeof bufBytes in the array object16Not applicable
strlen(buf)Characters before terminator5Not applicable
sizeof msgSize of the pointer itselfNot applicable8 on a 64-bit PC, 4 on most MCUs
strlen(msg)Characters before terminatorNot applicable8

The last sizeof row catches many students. When you hold a pointer, sizeof gives the pointer size, never the text length. The same happens when you pass an array to a function: inside the function the parameter is just a pointer.

Writing Your Own strlen in C: Two Versions

Building the function yourself removes the mystery. Both versions below prefix the name with ep_ so they never clash with the library. They also take const char *, which tells the compiler and the reader that the function only reads the string.

Version 1: counting with an index

Start a counter at zero and walk forward while the current character is not the terminator. The counter is the answer.

Version 2: pointer subtraction

Remember where you started, advance a pointer until it reaches the terminator, then subtract. Subtracting two pointers into the same array gives the number of elements between them. This is the style the real C library implementations resemble, and it avoids a separate counter variable.

The loop condition can be written as *s != '\0' or simply *s. They are identical because the terminator has the integer value 0, which C treats as false, and every other character code is non-zero and therefore true.

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

size_t ep_strlen_idx(const char s[])
{
    size_t i = 0;
    while (s[i] != '\0')
        i++;
    return i;
}

size_t ep_strlen_ptr(const char *s)
{
    const char *start = s;
    while (*s)
        s++;
    return (size_t)(s - start);
}

int main(void)
{
    char buf[16] = "UART2";
    const char *msg = "firmware";

    printf("sizeof(buf)        = %zu\n", sizeof buf);
    printf("strlen(buf)        = %zu\n", strlen(buf));
    printf("ep_strlen_idx(buf) = %zu\n", ep_strlen_idx(buf));
    printf("ep_strlen_ptr(msg) = %zu\n", ep_strlen_ptr(msg));
    printf("sizeof(msg)        = %zu (pointer size, not text)\n", sizeof msg);
    return 0;
}
$ gcc -std=c17 -Wall -Wextra -o ex9_strlen ex9_strlen.c
$ ./ex9_strlen

Expected output:

sizeof(buf)        = 16
strlen(buf)        = 5
ep_strlen_idx(buf) = 5
ep_strlen_ptr(msg) = 8
sizeof(msg)        = 8 (pointer size, not text)

Read the output line by line. The array is 16 bytes but the text is 5 characters. Both of your own functions agree with the library. The pointer msg reports a size of 8 bytes on a 64-bit machine, which has nothing to do with the 8 characters in the word firmware; that match is a coincidence of this example. On a 32-bit microcontroller the same line would print 4.

ep_strlen_ptr walking the word “adc”
startsadc\0
step 0s at astep 1s at dstep 2s at c
stops at \0s – start = 3

The size_t Trap You Must Know

Because strlen returns an unsigned value (a fact every strlen in C tutorial should stress), subtracting a longer length from a shorter one does not produce a negative number. It wraps around to an enormous positive value. Code that tests strlen(a) - strlen(b) < 0 is therefore always false. The compiler even says so when you enable warnings.

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

int main(void)
{
    const char *shortw = "adc";
    const char *longw  = "calibration";

    if (strlen(shortw) - strlen(longw) < 0)
        puts("shortw is shorter (what you expected)");
    else
        puts("surprise: unsigned subtraction wrapped around");

    if (strlen(shortw) < strlen(longw))
        puts("compare directly: shortw is shorter");

    printf("difference as size_t: %zu\n", strlen(shortw) - strlen(longw));
    return 0;
}
$ gcc -std=c17 -Wall -Wextra -o ex9b_unsigned ex9b_unsigned.c
ex9b_unsigned.c:9:40: warning: comparison of unsigned expression in '< 0' is always false [-Wtype-limits]
$ ./ex9b_unsigned
surprise: unsigned subtraction wrapped around
compare directly: shortw is shorter
difference as size_t: 18446744073709551608

The giant number printed at the end is 2 to the power 64 minus 8 on a 64-bit machine. The cure is to compare the two lengths directly, as the second if does: strlen(a) < strlen(b). Never subtract unsigned lengths unless you have already proven which one is larger.

Performance: strlen in C Costs O(n)

There is no stored length. Every call walks the whole string, so its cost grows with the text. That makes this innocent-looking loop quadratic:

for (size_t i = 0; i < strlen(line); i++) {
    /* strlen runs again on every iteration */
}

For a 40-character line that is 40 walks of up to 40 characters. Compute the length once into a variable, or stop the loop on the terminator itself. Optimising compilers can sometimes hoist the call, but only when they can prove the string does not change, so do not rely on it.

strlen in Embedded C Programming

On a microcontroller the string often lives in a receive buffer that an interrupt handler is filling. Two dangers appear that desktop examples hide:

  • Missing terminator. If the buffer was never terminated, strlen keeps reading past the end of the array until it happens to find a zero byte. The result is a wrong length, a hard fault, or a leak of neighbouring data. Always terminate receive buffers before measuring them.
  • Shared data. If an ISR can write to the buffer while the main loop calls strlen, the count may be stale or torn. Copy the data out inside a short critical section first.
  • Bounded variant. POSIX defines strnlen(s, max), which never reads more than max bytes. It is available in many embedded libraries such as newlib. Use it, or a loop with an explicit limit, whenever the source is not guaranteed to be terminated.

Common Mistakes with strlen in C

MistakeSymptomFix
Using sizeof on a pointer for the lengthAlways prints 4 or 8Use strlen for text length
Printing the result with %dWarning, wrong value on some platformsUse %zu
Allocating strlen(s) bytes for a copyOff-by-one overflow when the terminator is copiedAllocate strlen(s) + 1
Subtracting two lengthsWrapped huge valueCompare, do not subtract
Calling strlen on unterminated dataRunaway read, crashTerminate first or use strnlen
Calling strlen in a loop conditionSlow, quadratic timeStore the length once

Best Practices

  • Declare string parameters as const char * when you only read them; this is the standard signature of strlen in C itself.
  • Keep a length variable next to every buffer that you fill gradually, so you do not recount.
  • Use size_t for lengths and indices that you compare with strlen results.
  • Treat any external data, from a UART, network or file, as possibly unterminated until you add the terminator yourself.

Key takeaways

  • strlen counts characters before the first '\0'; the terminator is not included.
  • sizeof measures storage, strlen measures text; they only agree by accident.
  • while (*s) works because the terminator equals zero.
  • The result is unsigned: compare, never subtract.
  • Each call is O(n); do not put it in a loop condition.

Conclusion

The humble length function teaches three big ideas that run through all C string work: strings are conventions on top of byte arrays, library functions trust you to keep that convention, and the standard types such as size_t have rules you must respect. With a solid grip on strlen in C, comparing two strings is the natural next step, and that is the subject of the next lecture.

Frequently Asked Questions

Does strlen count the null terminator?

No. It counts the characters before the first zero byte. The terminator needs one extra byte of storage but is not part of the length.

Why is the return type size_t and not int?

Object sizes can exceed the range of int on large systems, so the standard uses an unsigned type that can hold any object size. Print it with %zu.

What does strlen return for an empty string?

Zero. An empty string is an array whose first element is the terminator.

How can I get the array size instead of the text length?

Use sizeof on the array itself, in the scope where it is declared. Once it decays to a pointer the size information is lost.

Is it safe to call strlen on a string literal?

Yes. Literals are terminated and strlen only reads. Just remember that you cannot modify the literal itself.

What is strnlen and should I use it in firmware?

strnlen stops after a maximum number of bytes. It is part of POSIX and common in embedded libraries, and it is the safer choice for buffers that might lack a terminator.

Topics Covered

strlen in Cstring lengthsizeof vs strlensize_tpointer subtractionstrnlenembedded C programmingfree embedded C course

Keep Building Your C Skills for Free

Next: comparing strings with strcmp, including why the return value is only guaranteed by its sign. Continue the free C programming course.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →