473,387 Members | 1,757 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

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,stdin);

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 1792
* 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,stdin);

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,stdin);

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.nowrites:
* 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,stdin);
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_Keith) 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.orgwrote:
"Alf P. Steinbach" <al***@start.nowrites:
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
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...
2
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 ......
5
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...
16
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...
4
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...
1
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 =...
40
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...
15
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...
13
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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...
0
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,...
0
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...

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.