473,890 Members | 1,381 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
57 11804
Malcolm wrote:

"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.


The advice is correct (so far as it goes).
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?


Because /you/ are the one who does the discarding, and you *remember* (or
rather, your code does).
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.


It's trivial to wrap this up into a function that dynamically resizes a
buffer; in fact, several of us here have done so (and published our code).

--
Richard Heathfield : bi****@eton.pow ernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 14 '05 #31
Malcolm <ma*****@55bank .freeserve.co.u k> spoke thus:
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.
If by "users" you mean the mass of people who use their computers to
surf the web, then sure. Many people who require more from their
machines than web surfing, however, find command line and text-based
utilities to be far more useful. I am typing this post in a
text-based newsreader (tin) running on a FreeBSD box in Texas while I
sit comfortably in an office in a suburb near Atlanta. I use the mutt
mail reader for my mail, and it is both much faster and much easier to
use than Outlook. Even the GUI utilities that I'm forced to use as a
part of my job (Borland's C++ compiler and make utility and Microsoft
Visual SourceSafe) I find to be much more effective when run from a
DOS prompt. I don't feel that I'm alone in these preferences with
respect to the professional computing community.
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.
Since when is more quirky? more myfile.txt - what could be simpler?
I suspect that you are missing out in a big way by disregarding
command line utilities, unless of course you *do* treat your computer
as a toy.
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.


I agree insofar as the majority of computer users are not involved in
the programming and maintenance of the systems in question. Those who
are, as well as a number of flat-out enthusiasts, typically fall
squarely on the side of command-line utilities.

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cybers pace.org | don't, I need to know. Flames welcome.
Nov 14 '05 #32
On Sun, 14 Dec 2003 22:07:42 UTC, "Malcolm"
<ma*****@55bank .freeserve.co.u k> wrote:

"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.


We've seen you knows nothing about real computeing. Even as I type
this message in a GUI newsreader here are about 3 douzend console
programs active - whereas one of them does nothing but watching and
steering a GUI program for unattended process. Without active
stdin/stdout/stderr it would unable to do its work. This GUI program
runs 24h/7d unattended. It has its GUI only for the seldom case I like
to do some action manually or have a quick look at the logs. But the
latter would even so easy by a commandline program like less.

No, I don't use M$ software because M$ has proven itself to be
incompatible to anything - even to itself even in standard C.

My OS has the best possible GUI, yes - but even that is not enough for
lots of actions I have to do dayly. Nothing gives more flexibility in
work than a commandline interface - even as something gets done more
comfortable with the GUI.

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.


No, not always.
"more" does use redirection, and it is a quirky thing to use - basically a
patch on the other utilities not being GUI.
Absolutely wrong. You don't know how to combine streams to get theyr
full power.
I have never had any reason to
use the other utilities mentioned.
Hm, as a person who knows nothing as using a GUI to click around to
combine predefined codesecuences to a new game you knows at least not
even how to program really. As a real programmer you would not even
use a GUI (even as you may use a GUI oriented editor) to build
programs instead clicking around. You should know how to use make, how
to pipe the compiler listing into your editors command window to steer
it to help you to fix your self programmed bugs.
Not all the world is a Wintel box. ;-)

Just the vast majority of general-purpose computers in use today.


is unable to run windows. It has not even another kind of GUI. The
advertizing of M$ is nothing than marketing for dumb users. Windows
GUI gets quickly unuseable when it comes to real facts and not only to
click, click.

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.
Right, but that is nowhere the mayority of computers. You've seen the
computers inside your car, your TV, your DVD player, your switch, your
router, your hard disk, your, monitor, your keyboard, your printer,
your camera, phones? There are more computers in your househeld, your
car, your car radio, trains, aircrafts, ships, motor cycles, boats,
mashines, .... as you would dream off.
Computer are conquering dayly more new fields you would never think.

There are computers with more power on a single board that 10 PCs who
have a comfortable user interfaces - but no keyboard and no screen, no
printer, no mouse, no GUI. PCs are only an absolute minority of the
wide fields where computeres running. GUIs are used soldom - but
commandline oriented user interfaces sofrequent as sand on the sea.
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.

But there more computers in only mobile telephones than game consoles.
There are more computers in factories, stores, mashines and so on than
PCs. Not each PC uses a GUI, many modern PC have never seen an monitor
attached, many PCs have never seen an hard disk attached, so many PCs
are running without GUI. Many PCs have a GUI only for the dumb user
who works with only the single program they know of - but when the
technican comes it kicks the GUI away to show the facts.

But most of all them above are programmed in C.

--
Tschau/Bye
Herbert

To buy eComStation 1.1 in germany visit http://www.ecomstation.de

Nov 14 '05 #33
On Sun, 14 Dec 2003 23:11:13 UTC, "Malcolm"
<ma*****@55bank .freeserve.co.u k> wrote:
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. :)

It's only likely to succeed if it can protect the user from needing to use
the command shell. I can't use it since I need to run programs that only
work on Windows.

Ever when I have to use windows I have to use its console to get the
results I need quickly instead looking for looooong time on flying
things like folders or documents. Doing the same work on commandline
lets me get finished it long before the windows GUI ever has done the
first step.

Oh, yeah, on my OS I can use the GUI because it is more quickly, more
elegant, more solid. But even there it lefts administrative work done
better on commandline. That is because it costs more time to fire the
GUI program up and click around its GUI than simply start an (GUI)
editor from commandline giving it the file to edit as parameter. In
that case the GUI is for the dumb user who does not know what he is
doing and the flat file is for the expert - but the result would be
the same.

The dumb user will use a day to get it done by clicking though the GUI
- I use 5 minutes for the same by editing some lines in some
configuration files.

Oh, yes - windows is for dumb users only. Even an expert has too often
no chance to work quickly and more exact as the dumb wincrap GUI
allows.

--
Tschau/Bye
Herbert

To buy eComStation 1.1 in germany visit http://www.ecomstation.de

Nov 14 '05 #34
On Mon, 15 Dec 2003 06:44:30 UTC, Richard Heathfield
<do******@addre ss.co.uk.invali d> wrote:
Using a non-GUI compiler, for a simple program it is of course easier to
type "cc foo.c" and everything will work.
Still in full agreement. Surely this can't last?


NOT using the GUI of the compiler still speeds up the build process
significantly. When you've learned how to use make, your text editor
(GUI - but full flagged for the use as developer tool) you would never
miss the GUI until you have to run your GUI program. Oh, yeah, a GUI
driven debug may help you significantly to debug your multithreaded
(non)GUI application.
Okay, so where in that lot do I use my routines to connect to, or disconnect
from, an SMTP server? Ah...

find dev -name \*.c | xargs grep SMTP[CD]
Using Windows "find" we can look for files or folders named "myprog.exe ",
and the GUI leads us through it.
Yes, and it's *slow*. What's more, it's harder to use than a CLI (IMHO,
having tried both).


I use both for finding something - depending on the kind of work I
have to do. When you use a good GUI (windows ones is cramp) you ends
up in both cases exactly w3ith that you want. If you uses a good
command processor (not the DOS thing that comes with windoes - but an
intelligent one like sh or 4os2) and you have a brain then it would be
easy.
We can then double-click on the icons it
brings up to see what's in them.


Doesn't sound very scriptable to me.


Right - but often enough it would exactly fullify your needs. Else you
would use your commandline processor and its tools - when you're not
playing on windows.
However you do lose some flexibility -
you can't pipe to your own version of "sort" which handles numerical
values as numbers (so x2 is before x11), for instance.


That's not the only flexibility you lose.

<snip>
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. :)

It's only likely to succeed if it can protect the user from needing to use
the command shell.


On the contrary, it has already succeeded. Incidentally, just like Windows,
it gives the user the *choice* of a powerful[1] command shell, or a weak
but pretty GUI.


And now we come to the point of truth. Use eComStation to get both - a
powerfull shell which you can exchange to others when you likes and a
powerfull GUI that can be extended easy by lots of frewware tools and
by yourself as a prograsmmer.
[1] The default Windows command shell is nowhere near as powerful as Linux's
various shells, IMHO, but hey, you can always use Cygwin.


No wounder it is the same as you had with DOS, nothing new, too less
tools, too high limited.
I can't use it since I need to run programs that only
work on Windows.


Why not do the world a favour and port them to Linux? :-)

Why not use eComStation and use them without porting? There is an open
source tool that migrates windows programms (NT, 2K, XP) on the fly
and lets them run seamless. There are already any usefull linux
commandline tools and shells ported to be native eComStation
applications, including apache, perl, php... and least but not last
anything you need to develop C programs.

--
Tschau/Bye
Herbert

To buy eComStation 1.1 in germany visit http://www.ecomstation.de

Nov 14 '05 #35
Malcolm wrote:
The real answer is that stdin is seldom used in real programs.

^^^^ ^^^^
The world is not only black and white, so it would be hard to give an
*real* answer. :-)

-Robert

--
Robert Bachmann _ _
Ro************* @rbdev.net |_) |_)
| \.|_).

Nov 14 '05 #36
On Sun, 14 Dec 2003 23:36:10 UTC, Mark McIntyre
<ma**********@s pamcop.net> wrote:
Pray tell me, how /do/ you send an text without typing?


Switch your microphone on, start up voice type, navigate your GUY by
speaking to your computer, let it open your preferred word
processor/mail program and dictate the text and formatting, order it
to print the document, read it, navigate with voice inside the text,
command the correctios, command it to save the document or to mail it
to its destination.

It can be done since 1996.

--
Tschau/Bye
Herbert

To buy eComStation 1.1 in germany visit http://www.ecomstation.de

Nov 14 '05 #37
On Mon, 15 Dec 2003 05:46:17 UTC, "Mac" <fo*@bar.net> wrote:
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.


Actually system administrators hate GUI's because they (sysadmins)
sometimes have to do the same thing over and over to many computers, and
what they really want is a way to script the action, while still allowing
a certain number of intelligent variables.

This is why Microsoft is now working on the shell to beat all shells.
(We'll se if they succeed, but they have recognized the deficit and are
trying to fix it.)


Microsoft was saying the same more than 10 years ago. It repeats that
every year new but was never able to get it right. It had the chance
to come nearly that what OS/2 2.0 had done 11 years ago - but failed
even with XP to come nearly on that what OS/2 had brought.
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.


Yeah, but they are not wintel boxes, either, which is the claim you seem
to be trying to contradict.

Anyway, don't forget about routers and access points and so on. Behind the
scenes, they absolutely use command lines.

And don't forget about all the embedded systems that don't really have a
user interface at all. Processors in cars, for example.

Besides, a lot of people like command lines. I'm one of them. ;-)


Me too - but my system gives me the best of both worlds at once. I use
the GUI extensively - but commandline whenever it is more effective.

Currently I use a system with 512 MB RAM, 4 GUI applications and 8
command windows active beside some desktop objects spreaded over 4
virtual desktops - and have about 256 MB RAM free. No, its not
windows, its not linux - but a PC where both are installed and
bootable when I may need them.

--
Tschau/Bye
Herbert

To buy eComStation 1.1 in germany visit http://www.ecomstation.de

Nov 14 '05 #38

"The Real OS/2 Guy" <os****@pc-rosenau.de> wrote in message
We've seen you knows nothing about real computeing.
[ snip ]
No, I don't use M$ software because M$ has proven itself to be
incompatible to anything - even to itself even in standard C.

I rest my case.
Nov 14 '05 #39

<ph************ **@ipal.net> wrote in message

Sure games are big, and there's money in games. But the real world is > no game. You better hope the game markets keeps going as I feel you could not make it in any other field.

What we're finding is that games are taking over a lot of serious
applications. Flight simulators are an obvious example. 3d graphics are
increasingly being used for other non-games, for instance to produce
architectural models. Then games and mobile phone apps are beginning to
merge. Finally, millions of consumers have a games console as their only
general-purpose computer.

However people aren't going to stop playing video games, and we have a fun
environment in which to work.

Nov 14 '05 #40

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

Similar topics

39
100836
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
1774
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
3962
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
9055
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
5317
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
2164
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
9980
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9829
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
11236
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
10836
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10926
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9643
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
8018
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
5856
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
4278
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.