Search code examples
cfgetsc-stringsgets

warning: the `gets' function is dangerous and should not be used


Hi when I write make in the terminal I get this message. What is the problem with gets? Must I change something. Thanks for helping.

user@ubuntu:~/Desktop/Project$ make
gcc -g -ansi -pedantic -Wall -lm project.o -o project 
project.o: In function `main':
project.c:(.text+0x2c8c): warning: the `gets' function is dangerous and should not be used.
void main(){
    char File_Name[55] = { "\0" };
    printf("Give Me File Name:\n");
    gets(File_Name);
    strcat(File_Name, ".as");
    Read_From_File(File_Name);
    printf("\n*******************************************\n");
    free_malloc();
}


Solution

  • The function gets is unsafe and is not supported by the C standard. The used array can be overwritten beyond its size. Instead use the function fgets. That is instead of this statement

    gets(File_Name);
    

    write at least like

    fgets( File_Name, sizeof( File_Name ), stdin );
    

    The function can append the new line character '\n' to the entered string. To remove it use the following code

    #include <string.h>
    
    //...
    
    fgets( File_Name, sizeof( File_Name ), stdin );
    
    File_Name[ strcspn( File_Name, "\n" ) ] = '\0';
    

    Take into account that this initialization

    char File_Name[55] = { "\0" };
    

    is equivalent to

    char File_Name[55] = "";
    

    or to

    char File_Name[55] = { '\0' };