Search code examples
cmemoryruntime-errorruntimegets

How can I use the "gets" function many times in my C program?


My code:

#include <stdio.h>
#include <math.h>
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        char a[10],b[10];
        puts("enter");
        gets(a);
        puts("enter");
        gets(b);
        puts("enter");
        puts(a);
        puts(b);
    }
    return 0;
}

Output:

1

enter 

enter

surya  (string entered by user)

enter

surya   (last puts function worked)

Solution

  • How can I use “gets” function many times in C program?

    You should never ever use gets() in your program. It is deprecated because it is dangerous for causing buffer overflow as it has no possibility to stop consuming at a specific amount of characters - f.e. and mainly important - the amount of characters the buffer, a or b with each 10 characters, is capable to hold.

    Also explained here:

    Why is the gets function so dangerous that it should not be used?

    Specially, in this answer from Jonathan Leffler.

    Use fgets() instead.


    Also the defintion of a and b inside of the while loop doesn´t make any sense, even tough this is just a toy program and for learning purposes.

    Furthermore note, that scanf() leaves the newline character, made by the press to return from the scanf() call in stdin. You have to catch this one, else the first fgets() thereafter will consume this character.


    Here is the corrected program:

    #include <stdio.h>
    
    int main()
    {
        int t;
        char a[10],b[10];
    
        if(scanf("%d",&t) != 1)
        {
            printf("Error at scanning!");
            return 1;
        }
    
        getchar();          // For catching the left newline from scanf().
    
        while(t--)
        {        
            puts("Enter string A: ");
            fgets(a,sizeof a, stdin);
            puts("Enter string B: ");
            fgets(b,sizeof b, stdin);
    
            printf("\n");
    
            puts(a);
            puts(b);
    
            printf("\n\n");
        }
    
        return 0;
    }
    

    Execution:

    $PATH/a.out
    2
    Enter string A:
    hello
    Enter string B:
    world
    
    hello
    
    world
    
    
    Enter string A:
    apple
    Enter string B:
    banana
    
    apple
    
    banana