By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,780 Members | 1,118 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,780 IT Pros & Developers. It's quick & easy.

Passing NULL to atoi() Function results in Segmentation Fault

P: 26
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.

Share this Question
Share on Google+
2 Replies


Banfa
Expert Mod 5K+
P: 8,916
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

P: 34
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.