I wrote this little program to practice arrays, which is supposed to take in a max of 10 characters, and the ending \0. It works, but it works too well, and even if I put in a 50 character name, it spits out the correct input. What gives?
#include <stdio.h>
int main(int argc, char const *argv[])
{
char name[11];
printf("Enter your name: ");
scanf("%s", name);
printf("Hi, %s\n", name);
return 0;
}
You are overwriting past the end of the array that you allocated – you need to specify as part of the scanf the length of the string to be read to make sure that it fits.
An improvement to your code would be to generate the format string so that it always has the right size.