473,804 Members | 2,111 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
14 22011


lovecreatesbeau ty wrote On 07/18/06 11:29,:
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?
Try the experiment yourself. For each of these
programs:

/* Program S */
#include <stdio.h>
int main(void) {
int x;
for (;;) {
puts ("Enter a value:");
if (scanf("%d", &x) == 1)
break;
puts ("Try again, please.");
}
printf ("The number is %d\n", x);
return 0;
}

/* Program SS */
#include <stdio.h>
int main(void) {
int x;
for (;;) {
char buff[100];
puts ("Enter a value:");
if (fgets(buff, sizeof buff, stdin) == buff
&& sscanf(buff, "%d", &x) == 1)
break;
puts ("Try again, please.");
}
printf ("The number is %d\n", x);
return 0;
}

.... enter WHAT_VALUE_ABC at the first prompt and 42 at
the second. Are there any differences in behavior? If
so, which behavior do you think is more useful in an
interactive setting? Why?

--
Er*********@sun .com

Jul 18 '06 #11
lovecreatesbeau ty wrote:
>
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.
scanf can be used more powerfully than that:

/* BEGIN new.c */
/*
** If rc equals 0, then an empty line was entered
** and the array contains garbage.
** If rc equals EOF, then the end of file was reached.
** If rc equals 1, then there is a string in array.
** Up to LENGTH number of characters are read
** from a line of a text file or stream.
** If the line is longer than LENGTH,
** then the extra characters are discarded.
*/
#include <stdio.h>

#define LENGTH 80
#define str(x) # x
#define xstr(x) str(x)

int main(void)
{
int rc;
char array[LENGTH + 1];

puts("The LENGTH macro is " xstr(LENGTH));
fputs("Enter a string with spaces:", stdout);
fflush(stdout);
rc = scanf("%" xstr(LENGTH) "[^\n]%*[^\n]", array);
if (!feof(stdin)) {
getchar();
}
while (rc == 1) {
printf("Your string is:%s\n\n"
"Hit the Enter key to end,\nor enter "
"another string to continue:", array);
fflush(stdout);
rc = scanf("%" xstr(LENGTH) "[^\n]%*[^\n]", array);
if (!feof(stdin)) {
getchar();
}
if (rc == 0) {
*array = '\0';
}
}
return 0;
}

/* END new.c */

--
pete
Jul 18 '06 #12
Eric Sosman wrote:
lovecreatesbeau ty wrote On 07/18/06 11:29,:
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?

Try the experiment yourself. For each of these
programs:

/* Program S */
#include <stdio.h>
int main(void) {
int x;
for (;;) {
puts ("Enter a value:");
if (scanf("%d", &x) == 1)
break;
puts ("Try again, please.");
}
printf ("The number is %d\n", x);
return 0;
}

/* Program SS */
#include <stdio.h>
int main(void) {
int x;
for (;;) {
char buff[100];
puts ("Enter a value:");
if (fgets(buff, sizeof buff, stdin) == buff
&& sscanf(buff, "%d", &x) == 1)
break;
puts ("Try again, please.");
}
printf ("The number is %d\n", x);
return 0;
}

... enter WHAT_VALUE_ABC at the first prompt and 42 at
the second. Are there any differences in behavior? If
so, which behavior do you think is more useful in an
interactive setting? Why?
/*scanf and sscanf are very similar. I can think of two differences
between them, one is sscanf needs one more argument, the other is the
difference demonstrated by the example code. but that can be fixed, see
line 9. please correct me if I am wrong.*/

/* Program S.2 */
#include <stdio.h>
int main(void) {
int x;
for (;;){
puts("Enter a value:");
if (scanf("%d", &x) == 1)
break;
while ((x = getchar()) != '\n' && x != EOF) ; /*line 9*/
puts ("Try again, please.");
}
printf ("The number is %d\n", x);
return 0;
}

Jul 19 '06 #13
lovecreatesbeau ty wrote:
>
/*scanf and sscanf are very similar. I can think of two differences
between them, one is sscanf needs one more argument, the other is the
difference demonstrated by the example code. but that can be fixed, see
line 9. please correct me if I am wrong.*/

/* Program S.2 */
#include <stdio.h>
int main(void) {
int x;
for (;;){
puts("Enter a value:");
if (scanf("%d", &x) == 1)
break;
while ((x = getchar()) != '\n' && x != EOF) ; /*line 9*/
puts ("Try again, please.");
}
printf ("The number is %d\n", x);
return 0;
}
Good: You've spotted the difference -- but you haven't
thought about it enough yet. Exercise: Modify the program
to read an integer from one line and a double from another,
prompting with "Enter an integer" and "Enter a double".
Test it by entering "42" on the first line and "42.0" on
the second. Then run it again, but this time enter "4 2"
on the first line. Run it a third time, entering "42 BAD"
on the first line and "BAD 42.0" on the second. Run it a
fourth time, entering " " at each prompt. Try to emit error
messages that describe as accurately as possible just how the
input differs from what the program expects.

The fundamental reason that fscanf() is not very good for
interactive input is that much interactive input is line-oriented,
but fscanf() is very nearly oblivious to line boundaries. fgets()
can provide the line awareness and then sscanf() can perform the
parsing, with the knowledge that it's operating on a line and not
on a stream of input that crosses an arbitrary number of line
boundaries, possibly more or fewer than you were expecting.

It is *possible* to do interactive input with fscanf(),
just as it is *possible* to write full-fledged C programs without
for, do, while, and if. Nobody will forbid you to indulge in
self-imposed hardships if that's your pleasure, but many will
wonder why you insist on doing things the hard way.

--
Eric Sosman
es*****@acm-dot-org.invalid
Jul 19 '06 #14
iwinux wrote:
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?
As with any problem, to solve it you must first understand the nature
of the problem. scanf() forces all destination variables to be
predclared before the input starts. So using scanf itself is the
source of the problem. In general its preferable to obtain the input
from some other method (an iterated fgets is possible, but hardly
ideal) then use *sscanf()* AFTER deciding on how much memory to malloc
for your destinations.

(Another problem is that more than likely you don't want to scanf()
parsing semantics. Strings are terminated by white space with scanf()
for some inexplicable reason.)
(I mean, no matter how many charaters you type in, it can works well.)
Anyhow, first lets start with getting a full line of input safely (C
doesn't have any built-in provisions for doing this):

http://www.pobox.com/~qed/userInput.html

The key point being that using fgetstralloc(), you know the length of
the input and have a the entire contents of the input in one shot (most
other programming languages have a built-in mechanism for doing this,
BTW). From there you can estimate the destination sizes, or use
strcspn() to help you parse before you figure out exactly how much
memory you need for your destination parameters, then use sscanf() or
whatever to extract the exact results.

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

Jul 19 '06 #15

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
11793
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
9876
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
3506
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
3179
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
17523
by: Martin Jørgensen | last post by:
Hi, Consider: ------------ char stringinput ..bla. bla. bla. do {
20
11025
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
2580
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
9595
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
10600
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
10354
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
10097
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...
1
7642
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
5535
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
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3835
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3002
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.