# What's wrong with this? strtok, atoi... [C++]



## demortes (Mar 19, 2007)

I keep getting a Segfault on the first atoi().

Why?

Thanks for any help in advance.


```
int load_pricelist()
{
  ifstream fList;
  string line;
  char *cstr;
  int i = 0;
  char *temp;

  fList.open("price.lst");
  if (fList.is_open())
  {
    while (! fList.eof())
    {
      getline (fList, line);
      cstr = strdup(line.c_str());
      temp = strtok(cstr, "-");
      pricelist[i].type = atoi(temp);               //pricelist is defined globally
      pricelist[i].name = strtok(NULL, "-");
      temp = strtok(NULL, "\n");
      cout << temp;
      pricelist[i].value = atoi(temp);
      free(cstr);
      i++;
    }
    fList.close();
  } else {
    return 2;
  }

  return 1;
}
```


----------



## lotuseclat79 (Sep 12, 2003)

Hi dmortes,

If you are compiling with g++, then run your executable with gdb which should be good to go in debugging your c++ program. If you are not compiling in a c++ environment with a symbolic debugger, then I suggest you get into the habit of doing that - i.e. download gcc and gdb - g++ is a part of the gcc tool and when you install gcc, you get g++ for free. Not sure if gdb is a separate download or not.

You can then single step through your program statement by statement and even disassemble the statement into assembler and find out what is going on.

OTOH, why do you assume that a string token is an ascii number - i.e. what does the input look like in terms of text lines?

-- Tom


----------



## blaqDeaph (Nov 22, 2005)

Because you're not assigning any length to temp, only a 4byte pointer. So when you're doing the strtok() into temp, you're overwriting the buffer after that (whatever it may be) resulting in a seg fault.

char* temp and char temp[100] are similar but not identical


----------



## demortes (Mar 19, 2007)

Input file:


```
1-Tritanium-2.54
2-Scordite-200
```
I just realized for the VALUE parsing, I should use atof().

I used GDB and G++ in Ubuntu, GDB doesn't give anything helpful.

Also, when I use char temp[100], it doesn't compile


```
cgi$ ./compile
pricelist.cpp: In function âint load_pricelist()â:
pricelist.cpp:64: error: incompatible types in assignment of âchar*â to âchar [100]â
pricelist.cpp:67: error: incompatible types in assignment of âchar*â to âchar [100]â
```
P.S. How do you fix the output to PUtty with the weird A?


----------



## blaqDeaph (Nov 22, 2005)

Ok. First up getline() is to be used on a c style string, so declaring temp[100] and doing a getline(temp) would be much easier than trying to go through all those solving routines to get it into a c-string.

Another thing to remember is to test for NULL on your strtok.


----------

