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?
Use fgets() instead of gets()
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.
Suggest a safe substitute for
gets()
.In existing code, to substitute
gets()
, it may not be desired to usefgets()
as that function requires an additionalchar
to save the'\n'
which both functions consume, butgets()
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, usegets_sz(dest, sizeof dest)
If
dest
is a pointer to anchar
array of sizen
, usegets_sz(dest, n)
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 thatfgets()
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. :)