Tuesday, December 14, 2010

C segmentation fault in linux but working in windows

Recently i came across an unusual problem.
I wrote a program in C on a windows machine using Dev-C++ program. The program compiled and run successfully. When i tried to compile it on linux using gcc it compiled successfully but when running it produced a segmentation fault!


The error was in the use of atoi() and strtok.
I had a string in the form "10 20 30" and i wanted to split it using the space character and the convert the numbers to intergers. In windows when strtok reached the end and returned NULL atoi returned 0.
But in linux atoi with a NULL input produced the segmentation fault.

So the solution is to create a temp variable of char type and check if it is null before assigning the value to an int.

int number;
char *temp_atoi;
temp_atoi=(char*)malloc(10*sizeof(char));
    while(temp_atoi)
    {
    number=atoi(temp_atoi);
       if( number>=0 )
        {
            //Do something
        }
       temp_atoi = strtok(NULL, " ");
    }

I hope this helps someone! I lost a lot of time finding it out!

No comments: