#include<stdio.h>
#include<conio.h>
int main()
{
char test [7];
for(int i=0;i<10;i++)
scanf("%c",&test[i]);
puts(test);
getch();
return 0;
}
I am using DevC++ (University rules) and I know that gets() has no bounds check so I have intentionally used for() loop to enter a string. When I am entering a string greater than the size of the array, puts is printing an extra character. Why so ??
Sample Input: helloworld Output: hellowos
Sample Input: Hellopeople Output: Hellopep
It's because you're overflowing memory. Your array only has enough for seven characters and you try to populate it with ten:
You can fix it (including allowing for a string terminator) with something like:
If you want a hardened user input function with buffer overflow protection, something built from
fgets()
is generally the best way in standard C. Something like this, for example.