Search code examples
arrayscfor-loopc-stringsstrlen

C char array has different length than expected


I have a very simple code:

secret[]="abcdefgh";//this is declared in different function and is random word
int len=strlen(secret);//ofc it is 8 in this case
char word[len];
for(int a=0;a<len;a++){//expecting this will put '_' at positions 0-7
    word[a]='_';
}
printf("%d %s",(int)strlen(word),word);

However, strlen(word) returns 11 and word contains "________� @", thus there is some obvious memory leak I can't see. Any idea?


Solution

  • This character array initialized by a string literal

    secret[]="abcdefgh";
    

    has 9 elements because it also includes the terminating zero of the string literal. So the definition above is equivalent to

    secret[9]="abcdefgh";
    

    Function strlen returns the number of elements of a character array that are before the terminating zero. So in this declaration

    int len=strlen(secret);
    

    variable len is initialized by 8 As result declaration

    char word[len];
    

    is equivalent to

    char word[8];
    

    In this loop

    for(int a=0;a<len;a++){//expecting this will put '_' at positions 0-7
        word[a]='_';
    }
    

    all elements of the aray are set to '_'. The arry does not have the terminating zero. So applaying function strlen to the array has undefined behaviour.

    You could change the loop the following way

    int a = 0;
    for(;a<len - 1;a++){//expecting this will put '_' at positions 0-7
        word[a]='_';
    }
    word[a] = '\0';
    

    In this case function strlen would return number 7 and the program would be well-formed.