cstrlen

C strlen on char array


I'm new to programming, so I was practicing with C. Then I ran to a problem with my code:

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

int main()
{
    char a[] = "Hello";
    printf("Length of a: %lu\n", strlen(a));

    char b[] = {'H', 'e', 'l', 'l', 'o'};
    printf("Length of b: %lu\n", strlen(b));
}

I am expecting to get:

Length of a: 5
Length of b: 5

Instead, I'm getting:

Length of a: 5
Length of b: 10

I have tried different strings, but every time, b has double the length of a Why is the length of b is double of a?


Solution

  • This is undefined behavior because the b array has no null terminator. The strlen function is searching for that so it knows when to stop counting.

    So, what happens is it runs off the end of the array and keeps going until the OS segfaults or you encounter a byte with the value zero in memory that's not part of the array.

    To better understand the differences between your two arrays, read more here: Array Initialization

    Regarding your specific question:

    Why is the length of b is double of a?

    This is not guaranteed at all. It is happening to you by pure chance. To understand better, you'd need to look at the generated assembly for your program. It could be a result of how the compiler is arranging other parts of your program in memory, or it could just be that you're seeing a pattern that doesn't exist.