GIDForums  

Go Back   GIDForums > Computer Programming Forums > CPP / C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 02-Dec-2005, 07:21
nikp nikp is offline
Invalid Email Address
 
Join Date: Nov 2005
Posts: 7
nikp is on a distinguished road

Need help with "atol". Exceptions handling?


Hello everyone!

I am using atol to convert a string into a long number and I don't know how to handle the exceptions thrown, when the converted value overflows.

I wrote the following program to test the convertion.
CPP / C++ / C Code:
#include <iostream>

using namespace std;

int main() {
   long a;
   string temp;
	
   for(int i = 0; i < 5; i++) {
      try {
         cout << "Insert long number: ";
         getline(cin, temp);
	
         a = atol(temp.c_str());
	
         if(a == LONG_MIN || a == LONG_MAX)
            throw "\nError convering a. Converted value overflow!";
			
            cout << "a = " << a << endl;
      }
      catch(char* s) {
         cout << s << endl;
      }
   }

   return 0;
}

I tried something like
CPP / C++ / C Code:
if(a == LONG_MIN || a == LONG_MAX)
but it doesn't work. In what way could I solve this problem?

Thank you
  #2  
Old 02-Dec-2005, 08:51
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,623
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Need help with "atol". Exceptions handling?


Quote:
Originally Posted by nikp
Hello everyone!

I am using atol to convert a string into a long number and I don't know how to handle the exceptions thrown, when the converted value overflows.


In fact, if atol() overflows the result is undefined. So, you simply can't use atol() if you are concerned about overflows. Period. Full stop.

As a matter of fact, overflows are not detected (and can not be detected, and never have been detected) for arithmetic operations on C or C++ built-in integer data types (char, short, int, long: signed and unsigned variants of them). This is the source of a number of bugs in software all over the world, and occasionally they result in exploits of the dreaded "buffer overflow" kind.

In general if you want to detect overflow for an integer addition, you could do something like the following:

CPP / C++ / C Code:
/* 
 * illustration of overflow detection for addition
 * of two non-negative longs
 *
 * This test is valid for systems that use 2's
 * complement representation of integer data types.
 *
 * davekw7x
 *
 * Questions? Post an inquiry on gidforums.com
 *
 */
#include <stdio.h>
#include <limits.h>

int main()
{

  long x = LONG_MAX - 1;
  long y = 1234;/* 5678; */

  long z;

  z = x + y;

  printf("\n\nLONG_MAX = %ld\n\n", LONG_MAX);
  printf("Addition gives this result:  %ld +  %ld = %ld\n\n", x, y, z);

  if (z < 0) {
    printf("                      But :  There was an overflow.\n");
  }
  else {
    printf("                      And :  There was no overflow.\n");
  }

  return 0;
}

I suggest you look at results when adding two large numbers or one large number and one small number, etc.

Note well: This test is valid for addition of two non-negative longs.

Furthermore, it is guaranteed only for systems that use 2's complement representation of long ints. The C standard does not specify how integer data types are to be represented, but systems that you are likely to run across these days do use 2's complement.

Other cases of interest for addition:

If either of the ints is zero, no overflow is possible (obviously).

If one of the ints is positive and the other is negative no overflow is possible for addition.

If they are both negative, how would the test be affected? Try it--- this program will not detect overflow in this case, but it's easy to make a test that will be valid for this case.

How would you test for overflow upon subtraction (where either or both can be negative). For example, let x = LONG_MAX and let y = -5, and calculate x - y.

So, for obtaining user input, instead of atol(), you could write your own conversion function (converting the string entered by the user to a long). This function would probably involve addition and multiplication of the decimal digits, so you also have to know how to detect overflow in decimal integer multiplication as well as addition (left as an exercise for the interested reader).


You can search for C++ classes that detect integer overflow (something called safe integer classes or safeints or something like that).

Regards,

Dave

p.s. The C standard does not specify the number of bits that are used for longs. Some systems that I currently use have 32-bit longs and some have 64 (and there may be others that I haven't checked lately). The value LONG_MAX and LONG_MIN are macros that give values for each particular system.
 
 

Recent GIDBlogFirst week of IA training by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Opinion on my code and a c++ class question FlipNode CPP / C++ Forum 7 07-Feb-2006 08:15
Microsoft Word Event handling help... Arthur M MS Visual C++ / MFC Forum 0 03-Jan-2005 20:09
[Library]HTML Class & CGI handling dsmith C Programming Language 0 09-Feb-2004 08:51
[script] Handling Error 404 JdS PHP Code Library 0 19-Nov-2003 08:22
error handling code.. daveyp225 CPP / C++ Forum 0 26-Oct-2003 06:46

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 18:22.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.