The most important message for you is:
Never use gets
- it can't protect against buffer overflow. Your buffer can hold 9 characters and the termination character but gets
will allow the user to typing in more characters and thereby overwrite other parts of the programs memory. Attackers can utilize that. So no gets
in any program.
Use fgets
instead!
That said - what goes wrong for you?
The scanf
leaves a newline (aka a '\n'
) in the input stream. So the first gets
simply reads an empty string. And the second gets
then reads "surya".
Test it like this:
#include <stdio.h>
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
char a[10],b[10];
puts("enter");
gets(a); // !!! Use fgets instead
puts("enter");
gets(b); // !!! Use fgets instead
puts("enter");
printf("|%s| %zu", a, strlen(a));
printf("|%s| %zu", b, strlen(b));
}
return 0;
}
Input:
1
surya
whatever
Output:
enter
enter
enter
|| 0|surya| 5
So here you see that a
is just an empty string (length zero) and that b
contains the word "surya" (length 5).
If you use fgets
you can protect yourself against user-initiated buffer overflow - and that is important.
But fgets
will not remove the '\n'
left over from the scanf
. You'll still have to get rid of that your self.
For that I recommend dropping scanf
as well. Use fgets
followed by sscanf
. Like:
if (fgets(a,sizeof a, stdin) == NULL)
{
// Error
exit(1);
}
if (sscanf(a, "%d", &t) != 1)
{
// Error
exit(1);
}
So the above code will automatically remove '\n'
from the input stream when inputtin t
and the subsequent fgets
will start with the next word.
Putting it all together:
#include <stdio.h>
int main()
{
int t;
char a[10],b[10];
if (fgets(a,sizeof a, stdin) == NULL)
{
// Error
exit(1);
}
if (sscanf(a, "%d", &t) != 1)
{
// Error
exit(1);
}
while(t--)
{
puts("enter");
if (fgets(a,sizeof a, stdin) == NULL)
{
// Error
exit(1);
}
puts("enter");
if (fgets(b,sizeof b, stdin) == NULL)
{
// Error
exit(1);
}
puts("enter");
printf("%s", a);
printf("%s", b);
}
return 0;
}
Input:
1
surya
whatever
Output:
enter
enter
enter
surya
whatever
Final note:
fgets
will - unlike gets
- also save the '\n'
into the destination buffer. Depending on what you want to do, you may have to remove that '\n'
from the buffer.