Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 room for the 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading