Disable warning messages in GCC through header fil

2019-01-07 00:25发布

I am using the function gets() in my C code. My code is working fine but I am getting a warning message

(.text+0xe6): warning: the `gets' function is dangerous and should not be used.

I want this warning message not to pop up. Is there any way?

I am wondering that there might be such possibilities by creating a header file for disabling some warnings. Or is there any option during compiling that can serve my purpose? Or may be there is a particular way of using gets() for this warning not to pop up?

9条回答
来,给爷笑一个
2楼-- · 2019-01-07 01:14

Use fgets() instead of gets()

char buffer[BUFSIZ];
/* gets(buffer); */
fgets(buffer,sizeof(buffer), stdin);

The gets() function does not check the length of buffer and can write past the end and alter the stack. This is the "buffer overflow" you hear about.

查看更多
爷、活的狠高调
3楼-- · 2019-01-07 01:20

Suggest a safe substitute for gets().

In existing code, to substitute gets(), it may not be desired to use fgets() as that function requires an additional char to save the '\n' which both functions consume, but gets() does not save. Following is a substitute that does not require a larger buffer size.

Each gets(dest) is replace with:
If dest is an array, use gets_sz(dest, sizeof dest)
If dest is a pointer to an char array of size n, use gets_sz(dest, n)

char *gets_sz(char *dest, size_t size) {
    if (size <= 1) {
        if (size <= 0 || feof(stdin)) {
            return NULL;
        }
    }
    size--;
    size_t i;
    for (i = 0; i < size; i++) {
        int ch = getchar();
        if (ch == EOF) {
            if (i == 0)
                return NULL;
            break;
        }
        if (ch == '\n')
            break;
        dest[i] = (char) ch;
    }
    dest[i] = 0;
    return dest;
}
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-07 01:21

Contrary to popular opinion, not all programmers are equally inattentive to what they are writing. gets() will always be standard in C90, and it was put in the library for several good reasons. It's no more "dangerous" than any other string function when used appropriately, such as in program examples, documentation, unit test scaffolding, homework assignments, etc.

What's more, gets() enhances readability in a way that fgets() never will. And one never has to interrupt one's train of thought to look up what order to put its arguments in.

The following workaround uses my other favorite function to remove the newline. :)

 #define gets GET_LOST
 #include "stdio.h"
 #undef gets

 #include "limits.h"

 char *gets(char *s)
 {
    return strtok(fgets(s, INT_MAX, stdin), "\n");
 }
查看更多
登录 后发表回答