473,769 Members | 2,346 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Correct way of taking in two integers

The following code fragment prompts the user to enter two integers
separated by a space. It works the way I want it to, but a friend
said it's not correct and said it can cause a buffer overflow. I
don't really see anything wrong with it. Can someone enlighten me?
int main(void)
{
int i,j;
char buff[50];

printf("Enter two integers: ");
fflush(stdout);
fgets(buff,50,s tdin);

if (sscanf(buff,"% d%d",&i,&j) != 2) {
printf("\nYou must enter 2 integers!\n");
return -1;
}

printf("\n%d + %d = %d\n",i,j,i+j);

return 0;
}
Jul 19 '06 #1
4 1811
* Steve Carter:
The following code fragment prompts the user to enter two integers
separated by a space. It works the way I want it to, but a friend
said it's not correct and said it can cause a buffer overflow. I
don't really see anything wrong with it. Can someone enlighten me?

int main(void)
{
int i,j;
char buff[50];

printf("Enter two integers: ");
fflush(stdout);
fgets(buff,50,s tdin);

if (sscanf(buff,"% d%d",&i,&j) != 2) {
printf("\nYou must enter 2 integers!\n");
return -1;
}

printf("\n%d + %d = %d\n",i,j,i+j);

return 0;
}
It's not that it can cause a buffer overflow in the sense of storing
data beyond the end of the buffer, but that the buffer isn't large
enough, and can never be large enough, to tackle all input that is
otherwise valid but contains too many spaces.

Why don't you use fscanf, and dispense with the buffer?

Additional advice: in this interactive program it doesn't matter, but
it's a good habit to always present error messages on the standard error
stream, instead of the standard output stream; also, although -1 is an
old convention, EXIT_FAILURE is slightly more portable and clear.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 19 '06 #2
Steve Carter wrote:
The following code fragment prompts the user to enter two integers
separated by a space. It works the way I want it to, but a friend
said it's not correct and said it can cause a buffer overflow. I
don't really see anything wrong with it. Can someone enlighten me?
int main(void)
{
int i,j;
char buff[50];

printf("Enter two integers: ");
fflush(stdout);
fgets(buff,50,s tdin);

if (sscanf(buff,"% d%d",&i,&j) != 2) {
printf("\nYou must enter 2 integers!\n");
return -1;
}

printf("\n%d + %d = %d\n",i,j,i+j);

return 0;
}


What if the value represented by the string of digits
exceeds the maximum limit of int?

You maywant to try strtol instead.

For example:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <errno.h>

#define MYBUFSIZE 50

extern int snprintf(char *, size_t, const char *, ...);

int main (void)
{
signed int value;
long int try_strtol;
char buf[MYBUFSIZE];
if ( snprintf(buf, MYBUFSIZE, "%lu", ULONG_MAX) >= MYBUFSIZE )
{
fprintf(stderr, "snprintf: value truncated\n");
return EXIT_FAILURE;
}
if (sscanf(buf, "%d", &value) != 1)
return EXIT_FAILURE;

printf("Buffer contains %s\n", buf);
printf("Scanned value %d\n", value);
errno = 0;
try_strtol = strtol(buf, NULL, 0);
if (errno == ERANGE)
{
if (try_strtol == LONG_MAX )
fprintf(stderr, "Overflow while trying to convert %s to
long\n", buf);
return EXIT_FAILURE;
}

return EXIT_SUCCESS;
}
For example, on my system the
above program produces:

Buffer contains 4294967295
Scanned value 2147483647
Overflow while trying to convert 4294967295 to long

--
Hope this helps,
Steven

Jul 19 '06 #3
"Alf P. Steinbach" <al***@start.no writes:
* Steve Carter:
>The following code fragment prompts the user to enter two integers
separated by a space. It works the way I want it to, but a friend
said it's not correct and said it can cause a buffer overflow. I
don't really see anything wrong with it. Can someone enlighten me?
int main(void)
{
int i,j;
char buff[50];
printf("Enter two integers: ");
fflush(stdout);
fgets(buff,50,s tdin);
if (sscanf(buff,"% d%d",&i,&j) != 2) {
printf("\nYou must enter 2 integers!\n");
return -1;
}
printf("\n%d + %d = %d\n",i,j,i+j);
return 0;
}

It's not that it can cause a buffer overflow in the sense of storing
data beyond the end of the buffer, but that the buffer isn't large
enough, and can never be large enough, to tackle all input that is
otherwise valid but contains too many spaces.
So if the user enters

123 456

he might get an error message. That doesn't seem too bad, though I'd
probably use a buffer bigger than 50 characters.
Why don't you use fscanf, and dispense with the buffer?
For one thing, fscanf skips all whitespace -- including newlines.

The real problem is that if the input contains valid integers, but
their value exceeds INT_MAX, the behavior is undefined. (Most likely
you'll just get a garbabe value, but in principle anything can
happen.)

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jul 19 '06 #4
Keith Thompson <ks***@mib.orgw rote:
"Alf P. Steinbach" <al***@start.no writes:
Why don't you use fscanf, and dispense with the buffer?

For one thing, fscanf skips all whitespace -- including newlines.

The real problem is that if the input contains valid integers, but
their value exceeds INT_MAX, the behavior is undefined. (Most likely
you'll just get a garbabe value, but in principle anything can
happen.)
Garbage values are bad enough. They could easily look reasonable to your
error checking code, but be entirely wrong. Corrupt but innocent-looking
data is a bugger to detect, filter and correct.

Richard
Jul 19 '06 #5

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

Similar topics

29
7483
by: Chris Dutrow | last post by:
I searched around on the net for a bit, couldn't find anything though. I would like to find some code for a function where I input A Range Of Integers For example: Function( 1, 100 ); And the function will return me an array holding a random subset of integers in that range of a size that I specify So the Function would Probabaly look something like this:
2
6471
by: Sean Dockery | last post by:
Which is the following is correct? a) <form ... onSubmit="return checkData()"> b) <form ... onSubmit="return checkData();"> c) <form ... onSubmit="checkData()"> d) <form ... onSubmit="checkData();">
5
4370
by: Rich S. | last post by:
Hi, Is the code below the best way to have the less than function for an 80 bit bitset or is there something faster / better? When I populate this map with millions (... and millions) of sets it gets slower and slower, I'm looking to make it faster. Thanks
16
3392
by: aruna | last post by:
Given a set of integers, how to write a program in C to sort these set of integers using C, given the following conditions a. Do not use arrays b. Do not use any comparison function like if/then or switch-case c. you can use pointers only d. you cannot use any of the loops either.
4
1549
by: craig | last post by:
I need two methods that would allow me to extract the high and low words from in Int32. Does this look correct? Thanks!! private Int16 HighWord(Int32 Value) { Int16 newValue; newValue = (Int16)(Value >> 16);
1
2854
by: amitbadgi | last post by:
I am gettign this error, while migration an app to asp.net Exception Details: System.FormatException: Input string was not in a correct format. Source Error: Line 19: Dim enddate = request.QueryString("enddate") Line 20: Line 21: if cint(eventid) = "0" then
40
2186
by: Allan M. Bruce | last post by:
I am applying for my first jobs after completing my PhD. I have been asked by a company to go and take a C programming test to see how my C skills are. Apparantly this test is mostly finding errors in small snippets of code but I was wondering if anyone could give me tips on what kind of things I should be looking out for. The one area I dont feel confident in is how to declare arrays of pointers and initialising multi-dimensional arrays....
15
5406
by: Lennart | last post by:
Hi folks, I have created an animated image gallery in dhtml. It works fine in Internet Explorer. In Firefox, it only works if I ommit the DOCTYPE tag. The page is valid xhtml-strict but with a xhtml1-strict DOCTYPE, I get a dead script and dozens of error messages like "Error in parsing value in property 'width'. Declaration dropped." on Line 0. This page doesn't work in Firefox but is valid xhtml:...
13
10395
by: Jen | last post by:
One user of my application is experiencing an exception "input string not in correct format". But it makes no sense where it is occurring. It is occurring when a string from a textbox ("172") is being convert to an Int16 (using Convert.ToInt16). How can that be? There are other text boxes that are used in the identical fashion and they don't generate the exception. All there are many other machines running my application that don't...
0
9423
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
10210
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
10043
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
9990
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
9861
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
8869
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...
0
6672
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
5298
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...
3
2814
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.