Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

warning: implicit declaration of function ‘gets’; did you mean ‘fgets’? [-Wimplicit-function-declaration]

Tags:

c

I have just begun my programming journey. I code in the Ubuntu terminal. I am facing a problem while compiling a program where the gets() function is used.

#include<stdio.h>

/*example of multi char i/p function*/
void main()
{
    char loki[10];
    gets(loki);
    printf("puts(loki)");
}

The error I am getting is:

warning: 'implicit declaration of function ‘gets’; did you mean ‘fgets’? [-Wimplicit-function-declaration]
like image 572
Lokesh Jain Avatar asked Aug 25 '26 10:08

Lokesh Jain


1 Answers

gets was removed in C11, because it is impossible to use correctly. gets does not know how many characters it can store into the array and continues to write as many as the user provides, which leads to the program to have undefined behaviour - crashes, modification of unrelated data etc.

The fix is to use fgets instead, though keeping in mind that it leaves a newline in the buffer:

#include <stdio.h>

// example of multi char i/p function
int main(void)
{
    char loki[10];
    fgets(loki, 10, stdin);

    // now loki will have the new line as the last character
    // if less than 9 characters were on the line

    // we can remove the extra with `strcspn`:
    loki[strcspn(loki, "\n")] = 0;

    // this will print the given string followed by an extra newline.
    puts(loki);
}
like image 165