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.
scanf("%10s", name);
An improvement to your code would be to generate the format string so that it always has the right size.
#include <stdio.h>
int main(int argc, char const *argv[])
{
char name[11];
char formatstr[50];
snprintf(formatstr, sizeof(formatstr), "%%%ds", sizeof(name)-1);
printf("Enter your name: ");
scanf(formatstr, name);
printf("Hi, %s\n", name);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With