2015-04-29 32 views
-1

所以我宣佈指針看起來像從讀取的文件中獲取段錯誤到對象指針數組?

Items* _items[ARRSIZE]; 

基本上用它們作爲對象(一個用於肉,一個用於生產)陣列的目標數組,它是在運行時動態決定。我在構造函數中調用以下函數,並將其標識爲我在main函數之前保留段落的原因。

void Inventory::loadRecs(){ 
    datafile.open(_filename); 
    int i = 0; 

    char c; 
    //create fileif it doesnt exist 
    if(datafile.fail()){ 
     datafile.clear(); 
     datafile.close(); 
     datafile.open(_filename, ios::out); 
     datafile.close(); 
    } 
    else{ 
     //read from 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(); 
    } 
} 

我從閱讀的文本文件是相當簡單的閱讀像

P,123,胡蘿蔔,0.66,[NEWLINE] 第一個字符識別它是什麼樣的產品(肉或產生),並用加載函數讀入該行的其餘部分。

我的清單類看起來是這樣的:

class Inventory{ 
    char _filename[256]; 
    Item* _items[5]; 
    std::fstream datafile; 
    int _noOfItems; 
} 

而構造方法僅初始化一切,並呼籲loadsRecs(這是我從我段錯誤)

+0

'Item :: load()'是怎麼樣的? – timrau

+0

[不要使用datafile.eof(),它可能與你的問題有關。](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-認爲是錯誤的) – dwcanillas

+0

此外,最好使用RAII而不是明確的調用「open」和「close」。 – b4hand

回答

0

我敢打賭,你沒有初始化您的指針數組,因此您的nullptr檢查失敗,並且您正在調用delete上的垃圾指針導致未定義的行爲。

除非你有一個你從代碼中省略的構造函數,否則指針是default initialized會導致不確定的值。

由於在您顯示的代碼中,您使用的是new Produce;new Meat;,我假定您已經編寫了new Inventory;Inventory i;。相反,如果你包含括號(或括號在C++ 11中),例如new Produce();Inventory i{};,你會得到value initialization這將做你的指針zero initialization。這會導致你看似期待的行爲。

+0

不會物品_items [5];初始化它們? – user3551329

+1

在C++ 11中,數組的[默認初始化](http://en.cppreference.com/w/cpp/language/default_initialization)對值進行默認初始化。在這種情況下,你的值是指針*而不是*對象。因此,它們被初始化爲不確定的值,假設你的'Inventory'對象被默認初始化。 – b4hand