Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array limit doesn't work

Tags:

arrays

c

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;
}
like image 814
Adnan Khan Avatar asked Jun 02 '26 04:06

Adnan Khan


1 Answers

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;
}
like image 131
Adrian Cornish Avatar answered Jun 04 '26 00:06

Adrian Cornish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!