Passing NULL to atoi() Function results in Segmentation Fault

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Gobi Sakthivel
    New Member
    • Jan 2013
    • 26

    #1

    Passing NULL to atoi() Function results in Segmentation Fault

    Code:
    int main()
    {
        char* x = NULL;
        int i;
        i = atoi(x);
        printf("i = %d\n",i);
        return 0;
    }
    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 .
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    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.

    Comment

    • swapnali143
      New Member
      • Mar 2012
      • 34

      #3
      syntax of atoi() is as follow

      int atoi ( const char * str );

      Because NULL is not Type Safe its giving you segmentation fault

      Code:
      // Sample program to explain atoi()
              #include<stdio.h>
      	#include<stdlib.h>
      
      	int main ()
      	{
      		int i;
      		char buffer [256];
      
      		printf ("Enter a number: ");
      		fgets (buffer, 256, stdin);
      
      		i = atoi (buffer);
      		printf ("The value entered is %d.",i);
      
      		return 0;
      	}

      Comment

      Working...