fgets() vs scanf() – overflow

in.c

When receiving input string, we often want to ensure, that input will not overflow our buffer. We can use fgets() or scanf. The first function will place the null-terminator to the buffer, no matter what. The second one will place what it gets from the input (However, read Josh’s comment at the bottom of the page).

#include<stdio.h>

int main(void)
{
    int i, N = 5;
    char buffer[N];
    
    printf("Enter %d characters\n", N+1);
    
    scanf("%5s", buffer);   /* MUST check comments below on this page for this! */
    
    /* Clear trailing input */
    while(getchar() != '\n')
        /* discard */ ;
    
    
    for(i = 0 ; i < 5 ; ++i)
        printf("|%c|\n", buffer[i]);
    
    printf("End with scanf\n\n");
    
    /*****************************************************/
    
    printf("Enter %d characters\n", N+1);
    
    fgets(buffer, 5, stdin);
    
    for(i = 0 ; i < 5 ; ++i)
        printf("|%c|\n", buffer[i]);
    
    printf("End with fgets\n\n");
    
    return 0;
}

Output

Enter 6 characters
samaras
|s|
|a|
|m|
|a|
|r|
End with scanf

Enter 6 characters
samaras
|s|
|a|
|m|
|a|
||
End with fgets


RUN SUCCESSFUL (total time: 7s)

This code was developed by me, G. Samaras. However, I would like to thank Vart from C board for mentioning that.

Have questions about this code? Comments? Did you find a bug? Let me know! 😀
Page created by G. (George) Samaras (DIT)

4 thoughts on “fgets() vs scanf() – overflow

  1. “The first function will place the null-terminator to the buffer, no matter what. The second one will place what it gets from the input. ”

    That is so simplified it is incorrect. The reference page for scanf is clear on why your code overflows. The width specifier: “Specifies the maximum number of characters to be read in the current reading operation.” For the buffer, whose size was N, the correct number was 4, not 5, as the programmer assumes because you need to leave room for the terminating zero. fgets can also be used in an equally irresponsible way, just pass in a number a little too big. Either function, when correctly used, will produce a string.

    When I need to decide which function to use, it depends on whether the string could contain whitespace. The fgets function is much easier to use if an input string contains multiple words, whereas scanf, with the %s specifier, will stop reading once it encounters whitespace.

  2. Pingback: Quick and easy program

  3. Pingback: How does the fscanf function work? – Read For Learn

Leave a comment