Why does puts() print an extra character in the end?

911 Views Asked by At
#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

4

There are 4 best solutions below

0
On

It's because you're overflowing memory. Your array only has enough for seven characters and you try to populate it with ten:

char test [7];             // Array indexes 0-6 allowed.
for(int i=0;i<10;i++)      // Array indexes 0-9 used.
    scanf("%c",&test[i]);

You can fix it (including allowing for a string terminator) with something like:

char test [11];            // Array indexes 0-10 allowed.
for(int i=0;i<10;i++)      // Array indexes 0-9 used.
    scanf("%c",&test[i]);
test[10] = '\0';           // And add string terminator before puts().

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.

0
On

your test array is only 7 chars, while you read 10 chars into it via the for loop. This could crash.

Also puts will expect your string to be 0-terminated. You don't explicitly put a 0 after your chars, so the output will contain whatever garbage is after your chars, up until the first 0-byte.

0
On

You have a buffer overflow as you try to store 10 characters into a buffer that can at-most store 7 elements

char test [7];
for(int i=0;i<10;i++)
  scanf("%c",&test[i]);

You can fix this by making the buffer 10 elements(So that it can store 9 characters plus one for the \0 at the end) and using this:

char test [10]; //10 elements long
scanf("%9s",test); //Get at-most 9 chars

or you can use fgets too.

0
On

Your strings does not end with '\0'.