This is a read-only archive. No new posts or registrations. Privacy Page
Software

using the "gets()" function in C

2 min read

This thread's last reply is from . Advice, software, and links below may be out of date — treat specific steps and download links with caution.

Looking for the outcome? Ask AI

For the longest time I've been wanting to learn a new language and eventually got around to buying a book to help me with that(I ended up getting "C for Dummies"). The book is amazing and i've learned quite a bit in a short amount of time, but started to have problems when they introduced the "gets()" function. In the book they say not to use that function since it has security issues, but a lot of the examples that they've been using have contained the gets function and not only that but everytime i've had to write something that i to use gets, the compiler spits out a bunch of errors. I've been improvising by using "scanf" and the programs have been working fine like that but what I want to know is if the compiler that just wont accept gets or am I just screwing up when i'm writting these programs :smack:
Hi there,

gets does indeed have a security flaw, in that the size of the receiving buffer you provide it is not checked and you can't specify a limit on the number of characters to read (so it is easy to produce a buffer overflow error).

Rather than using scanf as a workaround, I'd go with fgets, since it is much closer to what you are trying to replace.

As for what the compiler is telling you, well it depends on the compiler you are using. gcc for example will produce a warning about the security issue, but will still compile the program. If the only warnings you are getting mention gets' security issue then you know there is nothing wrong with your program. If the errors are talking about something else, then you need to look at your code.

Hope that helps, let me know if you have any more questions.
I rewrote the program and it ended up working (turns out the errors were made by me :smack: )

I tried replacing scanf with fgets but then I get an error saying "too few arguments to function ‘fgets’ "
fgets needs a couple more parameters than gets, since we also need to specify the buffer size, and the file we're reading from (stdin in this case).

So, where you might have had code that looked like this:
char buffer[50];
gets(buffer);
it should now look like this:
char buffer[50];
fgets(buffer, 50, stdin);

More info on fgets here:
http://www.cplusplus.com/reference/clibrary/cstdio/fgets/

Hope that helps.

Ask AI

AI can make mistakes. Check the cited posts. Archived advice can be out-of-date

Don't include personal information. Questions and selected public posts go to OpenAI. About Ask AI