0

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?
Joseph D.
  • 11,804
  • 3
  • 34
  • 67
  • 1
    You're writing to memory you didn't allocate all over the place (starting with your first `strcat()`, and continuing every other line afterward until just before the last `printf()`), which leads to all kinds of strange behavior. It might be beneficial for you to find a C tutorial. – Ken White Jul 11 '18 at 02:55

1 Answers1

1
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.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
  • Thank you! I changed char fmName[] = {}; to fmName[50]; and it seemed to solve my problem! –  Jul 11 '18 at 02:58