|
Luigi Auriemmaaluigi.org (ARCHIVE-ONLY FORUM!) |
|
It is currently 19 Jul 2012 11:54
|
View unanswered posts | View active topics
|
Page 1 of 1
|
[ 4 posts ] |
|
Author |
Message |
ape
|
Post subject: atoi() binary unsafe? Posted: 01 Dec 2009 03:27 |
|
Joined: 01 Dec 2009 03:25 Posts: 1
|
I recently was told I should use strtol instead of atoi...but I don't really see the rationale behind it.
|
|
Top |
|
|
hcs
|
Post subject: Re: atoi() binary unsafe? Posted: 01 Dec 2009 07:19 |
|
Joined: 16 Aug 2009 19:24 Posts: 29 Location: Austin, TX
|
atoi has no way to indicate an error. As the GNU manpage says:
The behavior is the same as strtol(nptr, (char **) NULL, 10); except that atoi() does not detect errors.
|
|
Top |
|
|
aluigi
|
Post subject: Re: atoi() binary unsafe? Posted: 01 Dec 2009 14:40 |
|
Joined: 13 Aug 2007 21:44 Posts: 4068 Location: http://aluigi.org
|
another alternative is using sscanf: if(sscanf(string, "%d", &number) == 1) printf("ok %d\n", number);
|
|
Top |
|
|
hcs
|
Post subject: Re: atoi() binary unsafe? Posted: 02 Dec 2009 13:39 |
|
Joined: 16 Aug 2009 19:24 Posts: 29 Location: Austin, TX
|
Your sscanf has half the issue of atoi: while it will correctly appear to fail if there are no decimal digits at the beginning of the string (optionally prefixed by whitespace), it will bail out when it hits invalid characters without reporting any errors. For instance: const char string[] = "123h"
|
|
Top |
|
|
|
Page 1 of 1
|
[ 4 posts ] |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot post attachments in this forum
|
|