Why does this C code change my variable lastName to another value without telling it to?

When I compile this code, the lastName variable is changed the third time I ask it to print it before telling it to change. What is causing this to happen?

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

 int main(void)
 {

    char firstName[] = "Bill";

    char middleName[] = "Bryan";

    char lastName[] = "Max";

    char fmName[] = {};

    char fmlName[] = {};

    printf("%s\n", lastName);

    strcat(firstName, middleName);

    printf("%s\n", lastName);

    strcpy(fmName, firstName);

    printf("%s\n", lastName);

    strcat(fmName, lastName);

    printf("%s\n", fmName);

    return 0;

 }

OUTPUT

>>> Max
>>> Max
>>> BillBryan // <- Why is it printing that lastName is this value when I did not change it?

1 answer

  • answered 2018-07-11 02:55 Silvio Mayolo

    char firstName[] = "Bill";
    

    This is making an array containing five elements: B, i, l, l, and \0.

    strcat(firstName, middleName);
    

    This is taking and overwriting the null at the end, then overflowing. You're writing to memory out of the bounds of firstName. This is undefined behavior, which means anything could happen. In practice, the latter local variables are likely being overwritten, which explains the symptoms you're seeing. But the point is you've hit UB, which means anything could happen.