Yotam
Yotam

Reputation: 10685

I can't understand why map cause segmentation fault

I have a loop that does the following:

short fooID;
char line[256]
map<short,foo> foos;
set<short> barIDs;
while (fgets(line,256,file) != NULL){
  string line_copy = line;
  /*use token to split the line into several parameters which does not effect foo * bar*/
  string token = strtok(line,",");
  token = strtok(NULL,",");
  token = strtok(NULL,",");
  token = strtok(NULL,",");
  token = strtok(NULL,",");
  barID = short(atoi(token));
  foo * bar;
  bar = new foo;
  if(barIDs.find(barID) == barIDs.end()){
     barIDs.insert(barID);
     bar->setID(barID);
     this->foos[barID] = bar;
  }
}

When I run this code, I get a segmentation fault when all the bars are loaded from the file. the barID range is 1-1192.

Any thoughts?

Thanks

The code above is only a typed summery of my actual code

Upvotes: 0

Views: 1239

Answers (4)

ralphtheninja
ralphtheninja

Reputation: 133008

You have a local foos:

map<short,foo> foos;

But later you use this->foos to store bar

this->foos[barID] = bar;

Also, the map is storing foo, not foo*

Upvotes: 0

atzz
atzz

Reputation: 18010

OK, my guess is that you are crashing here:

barID = short(atoi(token));

If the last line of your data file has a line feed, then the last fgets read (before it returns NULL on EOF) will return a blank line. You are not checking for this condition. Similarly, you are not checking the result of strtok before passing it to atoi. And on the blank line, that result will be NULL. So atoi will crash.

That said, you are constantly changing the details so I have no way to know whether the described sequence of events has anything to do with your real code. This is not a great way to get help. I'd suggest you in the future provide an accurate code snippet (compilable is the best) and some details on the crash (normally it is not difficult to determine the location of the crash, at least).

Upvotes: 0

Ezekiel Rage
Ezekiel Rage

Reputation: 581

Please note that char * strtok ( char * str, const char * delimiters ) changes the contents of the str parameter (see C++ Reference on strtok). Maybe you should replace line with line_copy since you're declaring it as string line_copy = line;?

Upvotes: 0

Erik
Erik

Reputation: 91270

foo * bar;

This creates a variable bar pointing to a random location in memory. You need to make it point to a valid object: bar = new foo; - and remember to delete it when you're done, iterate over your map and delete all the foo's you added.

Upvotes: 2

Related Questions