c++ - Getting a segfault from a file read to an array of object pointers? -
so i've declared array of pointers like
items* _items[arrsize]; basically goal of using them array of objects (one meat, 1 produce) dynamically decided on run time. i'm calling following function in constructor , i've identified reason keep segfaulting before main function.
void inventory::loadrecs(){ datafile.open(_filename); int = 0; char c; //create fileif doesnt exist if(datafile.fail()){ datafile.clear(); datafile.close(); datafile.open(_filename, ios::out); datafile.close(); } else{ //read file while(!datafile.eof()){ if(_items[i] != nullptr){ delete _items[i]; } c = datafile.get(); if(c == 'p'){ _items[i] = new produce; } if (c == 'm'){ _items[i] = new meat; } datafile.ignore(); _items[i]->load(datafile); i++; datafile.ignore(); //ignore endl } _noofitems = i; datafile.close(); } } the text file i'm reading straight forward reading like
p,123,carrots,0.66,[newline] first character identifies kind of product (meat or produce) , rest of line read in load function.
my inventory class looks this:
class inventory{ char _filename[256]; item* _items[5]; std::fstream datafile; int _noofitems; } and constructor initializes , calls loadsrecs (which segfault from)
i'm willing bet aren't initializing array of pointers , check against nullptr failing, , calling delete on garbage pointer resulting in undefined behavior.
unless have constructor omitted code, pointers default initialized resulting in indeterminate values.
since in code have shown, using new produce; , new meat;, i'll assume have written new inventory; or inventory i;. if instead, included parenthesis (or braces in c++11) new produce(); or inventory i{};, value initialization zero initialization of pointers. result in behavior seemingly expect.
Comments
Post a Comment