473,796 Members | 2,465 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to use scanf() safely?

Hi.
Before I use scanf(), I must malloc the memory for it, like this:

//Start
char * buffer;

buffer = malloc(20);
scanf("%s", &buffer);
//End

As we know, if I type 30 characters in, something bad will happen.
So, how can I solve this problem?
(I mean, no matter how many charaters you type in, it can works well.)
Jul 14 '06 #1
14 22009
iwinux wrote:
Hi.
Before I use scanf(), I must malloc the memory for it, like this:

//Start
char * buffer;

buffer = malloc(20);
scanf("%s", &buffer);
//End

As we know, if I type 30 characters in, something bad will happen.
So, how can I solve this problem?
(I mean, no matter how many charaters you type in, it can works well.)
Don't use scanf, use something like fgets instead.
--
==============
Not a pedant
==============
Jul 14 '06 #2
iwinux schrieb:
Before I use scanf(), I must malloc the memory for it, like this:

//Start
char * buffer;

buffer = malloc(20);
scanf("%s", &buffer);
//End

As we know, if I type 30 characters in, something bad will happen.
So, how can I solve this problem?
(I mean, no matter how many charaters you type in, it can works well.)
scanf() cannot easily be used in a safe manner.
See past discussions and the FAQ for this.
Usually, one just uses fgets() (or getchar() in a loop).

Back to scanf():
If you have compile time limits, you can use

#define stringize(s) #s
#define XSTR(s) stringize(s)
#define BUFSIZE 20

char *buffer = malloc(BUFSIZE+ 1);
if (buffer) {
if (1 == scanf("%"XSTR(B UFSIZE)"s", &buffer) {
do_something(bu ffer);
}
}

Otherwise, you can do
int len;
char *format;
char *buffer;

len = 1 + snprintf(0, 0, "%%%lus", bufSize);
if (len 0) {
format = malloc(len);
buffer = malloc(bufSize+ 1);
if (format && buffer) {
snprintf(format , len, "%%%lus", bufSize);
if (1 == scanf(format, buffer)) {
do_something(bu ffer);
}
}
}

Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Jul 14 '06 #3
iwinux wrote:
Hi.
Before I use scanf(), I must malloc the memory for it, like this:

//Start
char * buffer;

buffer = malloc(20);
if (buffer == NULL) ...
scanf("%s", &buffer);
scanf ("%s", buffer); /* no & */
//End

As we know, if I type 30 characters in, something bad will happen.
So, how can I solve this problem?
(I mean, no matter how many charaters you type in, it can works well.)
There's a whole suite of different things you can do.
One is to tell scanf() how much space is available:

scanf ("%19s", buffer); /* 19 + 1 == 20 */

This will prevent scanf() from trying to store characters
beyond the end of the allocated memory, but it still isn't
wonderful: If you type "supercalifragi listicexpialido cious"
the buffer will receive "supercalifragi listi" and a zero
byte, and then the next input operation will start with
"cexpial... ". If you type "It is an Ancient Mariner" the
buffer will receive "It" and a zero byte, and the next
input operation will start with " is an...".

Experience suggests that scanf() is *not* a good
function for interactive input. It is often better to
read a line at a time with fgets() (not with gets(),
mind you!) and then extract data from the complete
line, possibly with sscanf(). fgets() has its own set
of problems, but they are usually easier to deal with
than those of the much more complex scanf().

--
Eric Sosman
es*****@acm-dot-org.invalid
Jul 14 '06 #4
iwinux said:
Hi.
Before I use scanf(), I must malloc the memory for it, like this:

//Start
char * buffer;

buffer = malloc(20);
What if malloc returns NULL?
scanf("%s", &buffer);
The & is incorrect.
//End

As we know, if I type 30 characters in, something bad will happen.
Right. Well, it might. Or it might try to lull you into a false sense of
security.
So, how can I solve this problem?
(I mean, no matter how many charaters you type in, it can works well.)
There is always a limit, of course. But if you are prepared to abandon
scanf, you can make the limit sufficiently large for any practical purpose,
without having stupidly large static arrays around the place.

http://www.cpax.org.uk/prg/writings/fgetdata.php contains an article I wrote
which deals with precisely this problem, and which comes up with some
practical solutions.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jul 14 '06 #5
There is always a limit, of course. But if you are prepared to abandon
scanf, you can make the limit sufficiently large for any practical purpose,
without having stupidly large static arrays around the place.
So it's not easy to deal with a very long string?
Such as an text editor.
Jul 14 '06 #6
iwinux said:
>There is always a limit, of course. But if you are prepared to abandon
scanf, you can make the limit sufficiently large for any practical
purpose, without having stupidly large static arrays around the place.

So it's not easy to deal with a very long string?
Define "easy". It's easy for me. I don't know whether it's easy for you.
Such as an text editor.
<shrugIf you're writing a text editor, the ability to handle arbitrarily
long strings is the least of your worries.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jul 14 '06 #7
Eric Sosman wrote:
There's a whole suite of different things you can do.
One is to tell scanf() how much space is available:

scanf ("%19s", buffer); /* 19 + 1 == 20 */

This will prevent scanf() from trying to store characters
beyond the end of the allocated memory, but it still isn't
wonderful: If you type "supercalifragi listicexpialido cious"
the buffer will receive "supercalifragi listi" and a zero
byte, and then the next input operation will start with
"cexpial... ". If you type "It is an Ancient Mariner" the
buffer will receive "It" and a zero byte, and the next
input operation will start with " is an...".
Before the coming input operation, the program can clear the remainder
characters and has a correct beginning.
Experience suggests that scanf() is *not* a good
function for interactive input. It is often better to
read a line at a time with fgets() (not with gets(),
mind you!) and then extract data from the complete
line, possibly with sscanf(). fgets() has its own set
of problems, but they are usually easier to deal with
than those of the much more complex scanf().
Do you think the fgets and sscanf combination is also a right candidate
for non-user-interactive input, e.g. file input? Which functions should
be used for file input? Thank you.

Jul 18 '06 #8
lovecreatesbeau ty wrote:
Eric Sosman wrote:
>>
Experience suggests that scanf() is *not* a good
function for interactive input. It is often better to
read a line at a time with fgets() (not with gets(),
mind you!) and then extract data from the complete
line, possibly with sscanf(). fgets() has its own set
of problems, but they are usually easier to deal with
than those of the much more complex scanf().

Do you think the fgets and sscanf combination is also a right candidate
for non-user-interactive input, e.g. file input? Which functions should
be used for file input? Thank you.
It depends on the "provenance " of the file. It's perfectly
all right to use fscanf() directly if you're sure that the file
adheres to the expected format (or if you're willing to accept
the consequences of a deviation). If a program writes a file,
rewinds it, and reads it back again, fscanf() seems fine. If
Program A writes the file and a "related" Program B reads it,
fscanf() with bare-bones error-checking may be good enough (one
still needs some error-checking in case A 1.1 writes something
that B 1.0 can't digest).

If the file comes from an "unrelated" program, one must be
more cautious when reading it. If you write a program intending
that it be used as "vmstat 10 | myprogram" you must be on guard
against "vmstat -p 10 | myprogram" or "iostat -xn 5 | myprogram"
or even "myprogram < /etc/passwd". It is usually sufficient to
terminate with regrets when unexpected input is detected, but the
detection itself is also usually important ...

For "untrusted" line-oriented files, fgets() is a good place
to start because it captures the notion of "line." (Imperfectly,
in the case of lines too long for the provided buffer, but you
can write a little extra code to deal with that or to detect it
and say "This line of >1023 characters didn't come from vmstat.")
Once you've got the line sitting in a character array, C has a
good assortment of surgical tools for dissecting it: there's
sscanf(), strtok() -- I use it unashamedly, with care -- strchr(),
the <ctype.harsenal , strtod(), and all the rest.

In extreme cases, you might even write a full-fledged parser
that recognizes the input as matching (or failing to match) a
formal grammar, and possibly verifies other constraints as well --
the XML fad is founded on the desire to be able to do this sort
of thing in a fairly mechanical fashion. Such a parser might or
might not need the notion of "line;" it depends on the format.

--
Eric Sosman
es*****@acm-dot-org.invalid
Jul 18 '06 #9
Eric Sosman wrote:
It is often better to
read a line at a time with fgets() (not with gets(),
mind you!) and then extract data from the complete
line, possibly with sscanf().
I once thought fgets and sscanf may be better than the single scanf. At
the moment, I do not have that feeling at all. sscanf and scanf come
from one same family, the defeats in scanf remain in sscanf. When a
user enters, e.g. "WHAT_VALUE_ABC ", both fail:
scanf("%d", &i);
or
sscanf(buf, "%d", &i);

The program validates the range of the data user provided, prompts
users to reenter proper data after invalid data provided. Isn't this
the right way?

Jul 18 '06 #10

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

Similar topics

39
100816
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:---------------------------------------------------------------------
57
11791
by: Eric Boutin | last post by:
Hi ! I was wondering how to quickly and safely use a safe scanf( ) or gets function... I mean.. if I do : char a; 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
12
9875
by: B Thomas | last post by:
Hi, I was reading O'Reilly's "Practical C programming" book and it warns against the use of scanf, suggesting to avoid using it completely . Instead it recomends to use using fgets and sscanf. However no explanation is offered other than that scanf handels end of lines very badly. I have exeperienced such problems when doing some numerical programming but never understood it. Things like some consequitive scanfs would not read in values...
17
3505
by: Lefty Bigfoot | last post by:
Hello, I am aware that a lot of people are wary of using scanf, because doing it improperly can be dangerous. I have tried to find a good tutorial on all the ins and outs of scanf() but been unsuccessful. Is there a well-respected (by the c.l.c crowd) book or tutorial that really covers scanf in detail?
33
3172
by: Lalatendu Das | last post by:
Dear friends, I am getting a problem in the code while interacting with a nested Do-while loop It is skipping a scanf () function which it should not. I have written the whole code below. Please help me in finding why such thing is happening and what the remedy to it is. Kindly bear with my English. int main ()
185
17482
by: Martin Jørgensen | last post by:
Hi, Consider: ------------ char stringinput ..bla. bla. bla. do {
20
11024
by: Xavoux | last post by:
Hello all... I can't remind which function to use for safe inputs... gets, fgets, scanf leads to buffer overflow... i compiled that code with gcc version 2.95.2, on windows 2000 char tmp0 = "ABCDEFGHI\0"; char buff; /* Input buffer. */ char tmp1 = "ABCDEFGHI\0";
51
2579
by: deepak | last post by:
Hi, For the program pasted below, scanf is not waiting for the second user input. Can someone suggest reason for this? void main() { char c;
0
9528
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
10456
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...
1
10174
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
10012
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
9052
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
7548
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
5442
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...
0
5575
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3731
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.