In order to make the problem clear, I add some debugging code in the original code.
This is really the right place to solve this problem, because it is caused by overflow.
#include<stdio.h>
int main(void)
{
char name[10],age[2],addr[50],gradyear[50];
/* Debugging Code Begin */
printf("name\t\t: %p %p\n", (void *)name, (void *)(name+9));
printf("age\t\t: %p %p\n", (void *)age, (void *)(age+1));
printf("addr\t\t: %p %p\n", (void *)addr, (void *)(addr+49));
printf("gradyear\t: %p %p\n", (void *)gradyear, (void *)(gradyear+49));
/* Debugging Code End */
printf("Enter your Name:");
scanf("%[^\n]%*c", name);
printf("Enter your Age:");
scanf("%[^\n]%*c", age);
printf("Enter your Address:");
scanf("%[^\n]%*c", addr);
printf("Enter your Year of Graduation:");
scanf("%[^\n]%*c", gradyear);
printf("Here are your student credentials:\n"
"Name:%s \nAge:%s \nAddress:%s \nYear of Graduation:%s \n"
, name, age, addr, gradyear);
}
When compiled by gcc(GCC 11.2.0), the debugging output is:
name : 0x7ff7b92ca726 0x7ff7b92ca72f
age : 0x7ff7b92ca724 0x7ff7b92ca725
addr : 0x7ff7b92ca6f0 0x7ff7b92ca721
gradyear : 0x7ff7b92ca6b0 0x7ff7b92ca6e1
As we can see, the address of the second byte of age is 0x7ff7b92ca725
, and the address of the first byte of name is 0x7ff7b92ca726
. The two addresses are adjacent.
So when we input a two-or-more-digit number and save it in the array of age, the overflow happens.
For example, when we scanf
a two-digit long number, say 25 and then age[0] has '2', and age[1] has '5' and the Null character will be stored into the first byte of name.
That's exactly why the string of name shows an unexpected blank.
When compiled by clang(clang-1300.0.29.30), the debugging output is:
name : 0x7ff7bda1271e 0x7ff7bda12727
age : 0x7ff7bda1269e 0x7ff7bda1269f
addr : 0x7ff7bda126e0 0x7ff7bda12711
gradyear : 0x7ff7bda126a0 0x7ff7bda126d1
Similar to the above situation, here, we can see the address of the second byte of age (0x7ff7bda1269f
) is adjacent to the address of the first byte of gradyear (0x7ff7bda126a0
). When the overflow happens, the output of age is the content of both age and gradyear concatenated together, such as 152015
.
Suggestion and solution : always remember to add one extra byte for a C-style string (Null-terminated String).
If you plan to have a size of two, make it three for the array.