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?
开发者_StackOverflowThanks
The code above is only a typed summery of my actual code
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.
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;
?
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).
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*
精彩评论