Luigi Auriemma

aluigi.org (ARCHIVE-ONLY FORUM!)
It is currently 19 Jul 2012 11:54

All times are UTC [ DST ]





Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 4 posts ] 
Author Message
 Post subject: atoi() binary unsafe?
PostPosted: 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
 Profile  
 
 
 Post subject: Re: atoi() binary unsafe?
PostPosted: 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
 Profile  
 
 Post subject: Re: atoi() binary unsafe?
PostPosted: 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
 Profile  
 
 Post subject: Re: atoi() binary unsafe?
PostPosted: 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
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 4 posts ] 

All times are UTC [ DST ]


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

Search for: