Re: atoi return
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Fri, 10 Oct 2008 15:49:02 -0700
"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"
.
- Follow-Ups:
- Re: atoi return
- From: Richard Heathfield
- Re: atoi return
- From: Bill Cunningham
- Re: atoi return
- References:
- atoi return
- From: Bill Cunningham
- Re: atoi return
- From: Keith Thompson
- Re: atoi return
- From: Bill Cunningham
- atoi return
- Prev by Date: Re: Way to view public function names in a library
- Next by Date: Re: How to get array size from a pointer?
- Previous by thread: Re: atoi return
- Next by thread: Re: atoi return
- Index(es):
Relevant Pages
|