0

The content of course.Code before and after strcpy(course.Name, b) is "This" and "Thisis", which seems like strcpy() is also concatenating the content of b to course.Code

typedef struct {
    char Code[4];
    char Name[2];
}Course;

int main() {
    char str[7] = "This is";
    char a[4], b[2];
    Course course;
    sscanf(str, "%s %s", a, b);
    strcpy(course.Code, a);
    printf( "%s\n", course.Code );
    strcpy(course.Name, b);
    printf( "%s\n", course.Code );
   return(0);
}
kenlukas
  • 3,616
  • 9
  • 25
  • 36
Richard Tran
  • 132
  • 1
  • 11

1 Answers1

3

You need five characters to store "This" and three to store "is" because each string is terminated by a zero. (Bonus point: You need eight to store "This is")

The raw memory in course is going to look like this:

Code[0] 'T'
Code[1] 'h'
Code[2] 'i'
Code[3] 's'
Name[0] 'i'
Name[1] 's'

Since there is no terminating zero on course.Code, printf will keep printing. It has no way of knowing you wanted it to stop after four characters. The fact that you didn't get unreadable garbage after "Thisis" is largely a matter of luck and/or compiler settings.

Tim Randall
  • 4,040
  • 1
  • 17
  • 39
  • 1
    Note also that it is not guaranteed that the storage for the `Name` member abuts the end of the storage for the `Code` member, although the observed behavior seems to show that in this case it does. The structure layout can include any amount of padding after each member. – John Bollinger Sep 06 '18 at 20:05
  • @JohnBollinger That's a good point. If there _was_ any padding between the structure members, `strcpy(course.Code, a);` would have copied the terminating zero _into the padding_ and tungts might never have noticed any unusual behavior. – Tim Randall Sep 06 '18 at 20:08
  • ... and this is but one reason why overwriting array bounds produces undefined behavior. – John Bollinger Sep 06 '18 at 20:13