470,862 Members | 1,455 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,862 developers. It's quick & easy.

Passing NULL to atoi() Function results in Segmentation Fault

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.     char* x = NULL;
  4.     int i;
  5.     i = atoi(x);
  6.     printf("i = %d\n",i);
  7.     return 0;
  8. }
This will results in Segmentation Fault.

when we pass NULL to atoi(or any functions like this) it is giving segmentation fault. My question is why they didnt check for NULL case( which should be given first priority) in such inbuilt implementations.
Jan 23 '13 #1

✓ answered by Banfa

Because the specification states that you will pass in a valid pointer to a string. Given that specification the check is just superfluous processing and in a language that is designed for portability and speed that is undesired.

The problem is them but rather the code that calls the function with data that is outside of the functions stated specification.

If there is a chance that the pointer is NULL the calling code should be checking for it.

2 14551
Banfa
9,065 Expert Mod 8TB
Because the specification states that you will pass in a valid pointer to a string. Given that specification the check is just superfluous processing and in a language that is designed for portability and speed that is undesired.

The problem is them but rather the code that calls the function with data that is outside of the functions stated specification.

If there is a chance that the pointer is NULL the calling code should be checking for it.
Jan 23 '13 #2
syntax of atoi() is as follow

int atoi ( const char * str );

Because NULL is not Type Safe its giving you segmentation fault

Expand|Select|Wrap|Line Numbers
  1. // Sample program to explain atoi()
  2.         #include<stdio.h>
  3.     #include<stdlib.h>
  4.  
  5.     int main ()
  6.     {
  7.         int i;
  8.         char buffer [256];
  9.  
  10.         printf ("Enter a number: ");
  11.         fgets (buffer, 256, stdin);
  12.  
  13.         i = atoi (buffer);
  14.         printf ("The value entered is %d.",i);
  15.  
  16.         return 0;
  17.     }
  18.  
Jan 24 '13 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

3 posts views Thread by Anks | last post: by
10 posts views Thread by Peter Dragun | last post: by
13 posts views Thread by N.S. du Toit | last post: by
6 posts views Thread by damian birchler | last post: by
1 post views Thread by Dawn Minnis | last post: by
17 posts views Thread by bofh1234 | last post: by
2 posts views Thread by luqman | last post: by
8 posts views Thread by Andrea | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.