且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

gcc为什么以及如何为gets()发出警告?

更新时间:2022-10-17 13:34:25

关于这个问题:



gets $ c>函数对于缓冲区溢出的风险是危险的,并且从标准 C 中丢失,按照 C11 $ c $标准。编译器可能会支持它们以实现对旧代码的向后兼容。



FWIW,此警告不是由 gcc 发出的本身。很可能, glibc 包含一个编译器发出警告的编译指示。 Ref



关于错误:



您有 -Werror 在编译语句中启用,它基本上要求 gcc 将任何警告视为错误。 / p>

while(1)
    {
        printf("\nEnter message : ");
        gets(message);

        //Send some data
        if( send(sock , message , strlen(message) , 0) < 0)
        {
            puts("Send failed");
            return 1;
        }

        //Receive a reply from the server
        if( recv(sock , server_reply , 2000 , 0) < 0)
        {
            puts("recv failed");
            break;
        }

        puts("Server reply :");
        puts(server_reply);
    }

    close(sock);
    return 0;
}

This is part of my program. When I compile and run it, I get an error. The error's message is

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

Regarding the issue:

gets() function is dangerous for the risk of buffer overflow and dropped from the standard C, as per C11 standard. Compilers may support them for backward compatibility for legacy codes.

FWIW, this warning is not issued by gcc all by itself. Most likely, glibc contains a pragma which causes the compiler to emit the warning. Ref

Regarding the error:

You have -Werror enabled in your compilation statement, which basically asks gcc to treat any warning as error.