PSXDEV snippets : Null terminator in char array

Question

Am I missing something obvious here or is it just wrong to do that ?

char test[16] = "YEAHYEAHYEAHYEAH";
int len = 16;
int main()
{
    char temp[len];
    for(int i = 0; i < len; i++){
        temp[i] = test[i];
    }
    printf("%s %s", test, temp);
    return 0;
}

outputs :

YEAHYEAHYEAHYEAH YEAHYEAHYEAHYEAHPY-ďż˝

Answer

impiaaa : You need to consider the null terminator. printf needs to have some way to tell how long the string is, and the convention is to have a character code of 0 at the end.

The compiler adds this for you in literals, but your test array doesn't have enough room for it.

(so, in this case, changing test to be 17 long, and setting len to 17 accordingly, should fix it)

Sources

https://discord.com/channels/642647820683444236/663664210525290507/844594647673602108