2017-05-25 33 views
3

下面的代碼顯示了分段錯誤。但是,當我引用cout << endl聲明時,它將排除seg故障。我還打印了一份沒有endl的聲明,並且在main()的開頭正好碰到了seg錯誤。有人可以幫我解決這個問題嗎?謝謝!奇怪的分割錯誤在主開始處

#include <iostream> 

using namespace std; 

typedef struct node{ 
    string city; 
    node * next; 
} Node; 

class Vertex{ 
    public: 
     Vertex(string cityName) { 
      x->city = cityName; 
      x->next = NULL; 
     } 

     void printCity() { 
      cout << x->city << endl; 
     } 

    private: 
     Node * x; 
}; 

int main() { 
    //cout << endl; 
    Vertex x("Phoenix"); 
    x.printCity(); 

    return 0; 
} 
+6

數據成員';它總是一個懸掛的指針。 – songyuanyao

+0

@songyuanyao你是什麼意思?我該如何解決這個問題? – aashman

+1

如果可能,不要使用原始指針,只要'Node x;'應該沒問題。如果必須在構造函數中添加'x = new Node;',那麼在使用它之前。 (並執行析構函數來刪除它,並複製/移動構造函數,賦值運算符,...請參見[三什麼規則?](https://stackoverflow.com/questions/4172722/what-is-三條規則)) – songyuanyao

回答

-1
#include <iostream> 
using namespace std; 

typedef struct node{ 
    string city; 
    node * next; 
}Node; 

class Vertex{ 
    public: 
     Vertex(string cityName) { 
      x = new Node(); 
      x->city = cityName; 
      x->next = NULL; 
     } 

     void printCity() { 
      cout << x->city << endl; 
     } 
     ~Vertex(){ 
      delete x; 
     } 
    private: 
     Node* x; 
}; 

int main() { 
    //cout << endl; 
    Vertex x("Phoenix"); 
    x.printCity(); 

    return 0; 
} 
+1

如果可以,請將指針的類型更改爲'unique_ptr',如果可能的話,OP應該被通知最佳實踐 – Curious

7

您不會出現在你的Vertex構造函數初始化被x。這會導致解除引用中的未定義行爲,因此它只在某些情況下崩潰的事實是偶然的和不相關的。您需要先修復您的未定義行爲:

爲什麼x是一個指針並不是特別清楚,因此可以考慮在其聲明中刪除間接引號。 (*)如果使用指針是故意的,則需要分配一些內存來保存結構並在取消引用x之前用它初始化x。

也有與此代碼的一些風格問題,這可能會導致你麻煩的路線:

  1. 你可能想在explicit功能符添加到您的構造函數,以避免意外string隱式轉換。
  2. 如果你保留指針字段,你幾乎可以肯定想要替換自動生成的構造函數(默認,複製)並實現析構函數。 (見Rule of Three
+2

這個答案可以從解釋如何解決它中受益。 OP很可能不是C++的專家,即使它在技術上是正確的,也不可能從您所說的內容中受益。 – Tas

+0

@我正在提煉它。 :-)如果您認爲有任何遺漏,請隨時編輯我更新的答案。 – pmdj

+0

這比接受的答案要好。 – Bernard

1

三更多的事情

  1. 你也可以使用一個unique_ptr,而不是原始指針,以確保你沒有內存泄漏,更改代碼到這個
  2. 此外,由於您接受通過值字符串,考慮將其移動到您的節點類實例(也可以將其轉發到node構造)
  3. 身高:nullptr爲NULL在C++ 11和超越

可能有代碼以x`未初始化此

#include <iostream> 
#include <memory> 

using namespace std; 

typedef struct node{ 
    string city; 
    node * next; 
} Node; 

class Vertex{ 
    public: 
     Vertex(string cityName) : x{std::make_unique<Node>()} { 
      x->city = std::move(cityName); 
      x->next = nullptr; 
     } 

     void printCity() { 
      cout << x->city << endl; 
     } 

    private: 
     std::unique_ptr<Node> x; 
}; 

int main() { 
    //cout << endl; 
    Vertex x("Phoenix"); 
    x.printCity(); 

    return 0; 
}