473,659 Members | 2,886 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

safe scanf( ) or gets

Hi ! I was wondering how to quickly and safely use a safe scanf( ) or gets
function... I mean.. if I do :

char a[256];
scanf("%s", a);
and the user input a 257 char string..
that creates a problem.. same for gets..

even if you create a char array that's 99999999999999 char long.. if the
user input something longer it will still be a bug.. and I don't want
this..

<OT>
C++ have std::string that dynamicaly realloc themself if they are running
too big, but what about us ?
</OT>

I though about using character input function, from stdin, and then create a
string with this single character, then appending this character to the then
end of a string, and if the string gets too small, realloc( ) a bigger
one.. however this is quite annoying to do this each time I want to read
input.. yes I could create a function with this.. and that's what I gonna
do.. however I was wondering what you C experts were doing to avoid a
segfault or a bug in a such situation

thanks !
Nov 14 '05 #1
57 11739
nrk
Eric Boutin wrote:
Hi ! I was wondering how to quickly and safely use a safe scanf( ) or
gets
function... I mean.. if I do :

I don't know of any safe way to use gets. Use fgets instead where you can
specify the maximum number of characters to read into your buffer. With
scanf, the same can be achieved by specifying a maximum field width in the
conversion specifier (see below).
char a[256];
scanf("%s", a);
and the user input a 257 char string..
that creates a problem.. same for gets..

even if you create a char array that's 99999999999999 char long.. if the
user input something longer it will still be a bug.. and I don't want
this..

You can avoid this problem by specifying the maximum field width in the
conversion specifier:
scanf("%254s", a);
which will read a maximum of 254 characters into "a". Read the
documentation of scanf for more details.
<OT>
C++ have std::string that dynamicaly realloc themself if they are running
too big, but what about us ?
</OT>

You'll have to roll your own unfortunately.. . but... (see below)
I though about using character input function, from stdin, and then create
a string with this single character, then appending this character to the
then
end of a string, and if the string gets too small, realloc( ) a bigger
one.. however this is quite annoying to do this each time I want to read
input.. yes I could create a function with this.. and that's what I
gonna
do.. however I was wondering what you C experts were doing to avoid a
segfault or a bug in a such situation

Several regulars in this group (CBFalconer, Richard Heathfield, Morris
Dovey) have developed functions that do something along the lines of what
you want. Even if you want to roll your own, search the archives for a
thread with subject "Reading a line from a file" to get the URLs for the
same, to get a feel for how to go about it.

-nrk.

ps: This question seems to crop up so often around here that perhaps it
should be added to the FAQ?
thanks !


Nov 14 '05 #2

"Eric Boutin" <er**@nic.nac.w dyn.de> wrote in message

Hi ! I was wondering how to quickly and safely use a safe scanf( ) or > gets function... I mean.. if I do :

The real answer is that stdin is seldom used in real programs. If the
program takes a few parameters from the user these are passed on the command
line, if it needs a large number of inputs these are given in an ASCII file,
and if it really needs interactivity then it uses a GUI.

There are plenty of functions knocking around that read an arbitrary-length
string from stdin. You only have to write these once.

The advice to replace gets() with a call to fgets() and throw away the
trailing '\n' is bad, since you replace undefined behaviour with wrong
behaviour on overflow. To use fgets() properly you have to take action on
overflow, which makes the program complex.


Nov 14 '05 #3
"Malcolm" <ma*****@55bank .freeserve.co.u k> writes:
The real answer is that stdin is seldom used in real programs.
I strongly disagree. In fact, to get any /real/ work done with a computer,
programs which read from standard input and write to standard output (AKA
filter programs) are absolutely mandatory, IMO.

Without filter programs, computers would be useless to me. (I would also
be unemployed, because my work would be impossible.)
if it needs a large number of inputs these are given in an ASCII file,
I don't understand. A text file can contain arbitrarily long lines, just
like standard input. How does reading from a file instead of standard
input change the situation?

(In fact, on many operating systems, standard input can be redirected
from a file, and a file name is provided for the terminal, so IMHO it
doesn't make much sense to distinguish between standard input and named
files.)
and if it really needs interactivity then it uses a GUI.


Again, if this is supposed to be general advice (it sounds as if it is,
sorry if I misunderstood you), I strongly disagree. Many people (including
myself) prefer non-GUI programs to GUI programs.

Martin
Nov 14 '05 #4

"Martin Dickopp" <ex************ ****@zero-based.org> wrote in
"Malcolm" <ma*****@55bank .freeserve.co.u k> writes:
The real answer is that stdin is seldom used in real programs.
I strongly disagree. In fact, to get any /real/ work done with a
computer, programs which read from standard input and write to
standard output (AKA filter programs) are absolutely mandatory,
IMO.

Sound like someone knows about a world which I know nothing about.
and if it really needs interactivity then it uses a GUI.


Again, if this is supposed to be general advice (it sounds as if it is,
sorry if I misunderstood you), I strongly disagree. Many people
(including myself) prefer non-GUI programs to GUI programs.

Then we realise that we are more probably dealing with an eccentric. GUIs
have swept the board for interactive programs.
I don't know about filter programs - maybe in mainframe environments with
non-user generated stdin. As a games programmer I would never use nor write
a program written in such a fashion.
Nov 14 '05 #5
Malcolm wrote:
"Eric Boutin" <er**@nic.nac.w dyn.de> wrote in message
Hi ! I was wondering how to quickly and safely use a safe scanf( ) or >
gets function... I mean.. if I do :

The real answer is that stdin is seldom used in real programs. If the
program takes a few parameters from the user these are passed on the command
line, if it needs a large number of inputs these are given in an ASCII file,
and if it really needs interactivity then it uses a GUI.


This is grossly untrue. *Many* real programs are filters, taking stdin as
the default source.

There are plenty of functions knocking around that read an arbitrary-length
string from stdin. You only have to write these once.

The advice to replace gets() with a call to fgets() and throw away the
trailing '\n' is bad, since you replace undefined behaviour with wrong
behaviour on overflow. To use fgets() properly you have to take action on
overflow, which makes the program complex.


This is ridiculous. Only someone who doesn't know how to discard the '\n'
properly could have written such drivel. Of course it is not "bad" to call
fgets() and discard the trailing '\n'. What is necessary is to decide what
to do when there is no trailing '\n', and the level of complexity involved
need not be large at all.

--
Martin Ambuhl

Nov 14 '05 #6
"Malcolm" <ma*****@55bank .freeserve.co.u k> wrote:

"Martin Dickopp" <ex************ ****@zero-based.org> wrote:
"Malcolm" <ma*****@55bank .freeserve.co.u k> writes:
The real answer is that stdin is seldom used in real programs.
I strongly disagree. In fact, to get any /real/ work done with a
computer, programs which read from standard input and write to
standard output (AKA filter programs) are absolutely mandatory,
IMO.

Sound like someone knows about a world which I know nothing about.


You don't know about operating systems providing command line
interfaces? Can't believe that.
and if it really needs interactivity then it uses a GUI.


Again, if this is supposed to be general advice (it sounds as if it is,
sorry if I misunderstood you), I strongly disagree. Many people
(including myself) prefer non-GUI programs to GUI programs.

Then we realise that we are more probably dealing with an eccentric.


Nobody preferring a console interface over a GUI is an eccentric,
but someone who knows about the power of command lines.
GUIs
have swept the board for interactive programs.
stdin and interactive input are not equivalent. In a typical
environment input and output of a program are often redirected
to/from other sources. Remember: stdin/stdout/stderr are streams
which may be connected to a console, or a physical file. From C's
POV there's no difference, hence the rule: never use gets (for
suitable values of 'never').
I don't know about filter programs - maybe in mainframe environments with
non-user generated stdin.
A lot of standard command line utilities on a vast number of OSs are
filter programs. For example, you virtually can't do anything useful
on a typical *nix system without using stream filters, e.g. grep,
head, tail, sed, awk, gzip, more, cut, sort, ...
As a games programmer I would never use nor write
a program written in such a fashion.


Not all the world is a Wintel box. ;-)

Regards
--
Irrwahn Grausewitz (ir*******@free net.de)
welcome to clc : http://www.angelfire.com/ms3/bchambl...me_to_clc.html
clc faq-list : http://www.eskimo.com/~scs/C-faq/top.html
acllc-c++ faq : http://www.contrib.andrew.cmu.edu/~a...acllc-c++.html
Nov 14 '05 #7

"Irrwahn Grausewitz" <ir*******@free net.de> wrote in message

Then we realise that we are more probably dealing with an eccentric.
Nobody preferring a console interface over a GUI is an eccentric,
but someone who knows about the power of command lines.

No its eccentric. Users generally won't accept command line programs unless
forced to use them. A GUI is generally far easier to use - I'm typing this
into a GUI newsreader.
A lot of standard command line utilities on a vast number of OSs are
filter programs. For example, you virtually can't do anything useful
on a typical *nix system without using stream filters, e.g. grep,
head, tail, sed, awk, gzip, more, cut, sort, ...
Well grep you would usually invoke with the name of the file to search.
"more" does use redirection, and it is a quirky thing to use - basically a
patch on the other utilities not being GUI. I have never had any reason to
use the other utilities mentioned.
Not all the world is a Wintel box. ;-)

Just the vast majority of general-purpose computers in use today. Even jobs
that used to require a mainframe can now often be done on PCs. Things like
supermarket checkouts and airport information screens are often PCs
underneath.
The vast majority of medium-sized systems that aren't PCs are probably games
consoles. They don't use command lines either. Nor do mobile phones.

Nov 14 '05 #8

"Martin Ambuhl" <ma*****@earthl ink.net> wrote in message

This is ridiculous. Only someone who doesn't know how to discard
the '\n' properly could have written such drivel.
Well the FAQ showed to "replace gets() with a call to fgets()", and
discarded the trailing '\n', which means that undefined behaviour on
overflow is very likely to be replaced by incorrect behaviour on overflow.

If an experienced programmer like Steve Summitt can't get it right, then I
think we can say that fgets() is difficult to use.
Of course it is not "bad" to call fgets() and discard the trailing '\n'.
What is necessary is to decide what to do when there is no trailing '\n',
So how do you determine if there is no trailing '\n', if it's been
discarded?
and the level of complexity involved need not be large at all.

It depends what you mean. If you are comparing to some sort of analysis of
equations used in particle physics then, no, its not complicated. If you
mean that it adds substantial extra hassle to what should be a simple
process of getting a line from the user, then, yes, using fgets() properly
is complicated. You need to check the '\n', then discard the remainder of
the line, report an error message to the user (probably), and then loop to
get another line.
Nov 14 '05 #9

On Sun, 14 Dec 2003, Malcolm wrote:

"Irrwahn Grausewitz" <ir*******@free net.de> wrote in message

Nobody preferring a console interface over a GUI is an eccentric,
Careful about those generalizations , Irrwahn -- I bet I could
provide a few counter-examples if provoked. :)
but someone who knows about the power of command lines.


No its eccentric. Users generally won't accept command line programs unless
forced to use them. A GUI is generally far easier to use - I'm typing this
into a GUI newsreader.


Yes, and that's precisely one of the examples I was going to
bring up prevthread, as one of your apps requiring "more complicated
input" than your average non-GUI app can deliver. Also text editors
and programs computation- or I/O-heavy enough to really *require* a
progress indicator (e.g., my system's default invocation of 'wget').
Line-based text editors do exist, but IMHO only eccentrics really
*do* use those. ;-)
However, I frequently use a command-line compiler (gcc), which
is IMHO orders of magnitude more powerful and user-friendly than
the typical Visual offering. And of course if you've ever used
an MS-DOS Command Prompt on your Wintel box, you've seen how programs
like 'copy' and 'dir' can be useful from time to time. :)

A lot of standard command line utilities on a vast number of OSs are
filter programs. For example, you virtually can't do anything useful
on a typical *nix system without using stream filters, e.g. grep,
head, tail, sed, awk, gzip, more, cut, sort, ...

Well grep you would usually invoke with the name of the file to search.


Yes, but you may not have known that you can *also* invoke 'grep'
like this:

c:\> grep 'hello' < myfile.txt
or
c:\> dir /s | grep "myprog.exe " | sort

which last is a complex operation which to my knowledge cannot be
performed by any of the out-of-the-box GUI tools on Windows XP
(although third-party tools exist, of course). See, command-line
tools can be very useful for the everyday tasks of people who know
and use computers every day -- even if gamers don't need them.

Not all the world is a Wintel box. ;-)


Just the vast majority of general-purpose computers in use today. Even jobs
that used to require a mainframe can now often be done on PCs. Things like
supermarket checkouts and airport information screens are often PCs
underneath.
The vast majority of medium-sized systems that aren't PCs are probably games
consoles. They don't use command lines either. Nor do mobile phones.


BZZT. How do you think those phones are programmed? I'm willing
to bet, even though I don't know, that the guys who work for Nokia
or whatever have on their desks little gray boxes with cords that
plug into ports on the phones and interface with the phone's
file system at a rudimentary command line level. Because line-
driven shells are easy to write, and GUIs are hard (generally
speaking).
And a note in passing to look up "Linux" sometime -- it looks
like it might be becoming more popular in both the commercial and
home markets. :)

-Arthur
Nov 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

39
100779
by: Teh Charleh | last post by:
OK I have 2 similar programmes, why does the first one work and the second does not? Basically the problem is that the program seems to ignore the gets call if it comes after a scanf call. Please anything even a hint would be really helpful, I cant for the life of me see why the 2nd prog wont work... gets before scanf code:---------------------------------------------------------------------
7
1761
by: sajjanharudit | last post by:
Can anyone explain me what is happening in the following code: #include<stdio.h> int main() { int i,j; scanf("%d %d" + scanf("%d %d",&i,&j)); printf("%d %d\n"); }
51
3859
by: moosdau | last post by:
my code: do { printf("please input the dividend and the divisor.\n"); if(!scanf("%d%d",&dend,&dor)) { temp1=1; fflush(stdin); } else
280
8873
by: jacob navia | last post by:
In the discussion group comp.std.c Mr Gwyn wrote: < quote > .... gets has been declared an obsolescent feature and deprecated, as a direct result of my submitting a DR about it (which originally suggested a less drastic change). (The official impact awaits wrapping up the latest batch of TCs into a formal amending document, and getting it approved and published.)
104
5199
by: jayapal | last post by:
Hi all, Whenever I use the gets() function, the gnu c compiler gives a warning that it is dangerous to use gets(). why...? regards, jayapal.
19
2144
by: subratasinha2006 | last post by:
I can not accept a string (without space) of length more than 127 whatever I do.. Entry is restricted by 127 characters. I have declared an array of size more than 200. or I have used dynamic memory allocation. But the echo is stopped
0
8332
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8851
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8627
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7356
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6179
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4175
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
1975
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1737
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.