Re: atoi return



"Bill Cunningham" <nospam@xxxxxxxxxxxxx> writes:
"Keith Thompson" <kst-u@xxxxxxx> wrote in message
news:ln4p3lm0yy.fsf@xxxxxxxxxxxxxxxxxx
Take a look at the following program and tell me how you'd detect an
error in a call to atoi().

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *good = "0";
char *bad = "bad";
printf("atoi(\"%s\") = %d\n", good, atoi(good));
printf("atoi(\"%s\") = %d\n", bad, atoi(bad));
return 0;
}

I can't really read that Keith but if I remember right this was
mentioned before but never really explained. I would've tried something
like this if it's even valid.
...
int i;
if (i=atoi(argv[1]))!=sizeof(int))
fprintf(stderr,"error\n");

*sigh* I dunno. Does this make any sense?

No, it doesn't. What does sizeof(int) have to do with anything?

Yes, this was mentioned before, and it was explained in great detail.

Here's the point. If you give atoi() a string that doesn't represent
a number, such as the string "bad", it returns 0. If you give it the
string "0", which does represent a number it returns 0. If atoi()
returns 0, you *can't tell* whether it successfully converted the
string "0" or failed to convert the string "bad".

Even worse, if atoi() is given a string that represents a number
that's too big to hold in an int, it invokes undefined behavior. For
example, there's no telling what atoi("99999999999999999999") will do;
it could crash your program or worse.

--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
.



Relevant Pages

  • Re: Check all errors in code?
    ... The atoi function converts the initial portion of the string ... pointed to by nptr to int representation. ... The atoi function returns the converted value. ... The strtol function returns the converted value, ...
    (comp.lang.c)
  • Re: Help with changing char *string to int * string for sorting.
    ... > I'm trying to sort integers from a text file. ... otherwise the string may not appear. ... It looks as if you have the impression that atoi() would convert all ... int x; ...
    (comp.lang.c)
  • Re: string to int
    ... >> atoi - Simplest but no error handling in case of bad input. ... > Well the thread started with a title such as "string to int" ...
    (microsoft.public.vc.language)
  • Re: string to int
    ... > atoi - Simplest but no error handling in case of bad input. ... Well the thread started with a title such as "string to int" ... So "int atoi" is as simple as it gets. ...
    (microsoft.public.vc.language)
  • Re: what is atoi( )
    ... The atoi function tries to convert an string to a integer number. ... int main (void) { ...
    (comp.lang.c)