Search code examples
csegmentation-faultatoi

Why do I get a segfault with atoi in c?


I'm trying to read a string from argv. It should be something like a mathematical function like "-x^2-5" etc.

I've got something like this:

void test(char *function){
  int temp = 0;
  for (int i = 0; i < strlen(function); i++){
    if((function[i] != '+') && (function[i] != ...){
      // function[i] is a digit, but still as a char
      temp = atoi(function[i]);
    }
  }
  //... 
}
int main(int argc, char **argv){
  test(argv[1]);
  //...
}

This works quite well until the last lap of the loop. If I use printf("%c", function[i]);, it sais, it's 5.

But atoi(function[i]) gives a segfault. Why?


Solution

  • Right. Let's first take a look at the signature of atoi.

    int atoi(const char *str);
    

    Now, what you are passing to it is function[i], and since function is of type char *, function[i] is a char. And your character is most likely not a proper character pointer.

    What you'd want to pass to atoi is instead a const char *, which you can get by calling atoi(&function[i]);