2016-07-26 8 views
0

私はタグクラスを実装していたのですが、C++の新機能です。ランタイムエラーが発生しました。 デバッグ時に、ランタイムエラーがポインタ(**)attrib_listをインクリメントすることによって発生したことがわかりましたが、同じメモリアドレスを指す他のポインタはインクリメント時にエラーを発生しません この奇妙な動作? 私はadd_attributeを2回呼び出した後、このコードポインタをインクリメントする際にランタイムエラーが発生しましたが、その理由は何ですか?

class Tag{ 
public: 
    Tag(): 
     tagname{""}, sz{0}, t_sz{0}, attrib_list{nullptr}, ptr_nav{nullptr}{ 
    } 

    Tag(string name, int n_att): 
     tagname{name}, sz{0}, t_sz{n_att}, attrib_list{new string*[n_att]}{ 
      for(int i=0; i<n_att; i++){ 
       attrib_list[i] = new string[2]; 
      } 
      ptr_nav = &attrib_list[0];  //take risk here 
    } 

    ~Tag(){ 
     for(int i=0; i< t_sz; i++){ 
       delete[] attrib_list[i]; 
      } 
     attrib_list = nullptr; 
     ptr_nav = nullptr; 
     t_sz, sz = 0; 
    } 


    // this function produces rintime error 
    void add_attribute(string name, string value){ 
     (*attrib_list)[0] = name; 
     (*attrib_list)[1] = value; 
     sz++; 
     attrib_list++; 
    } 


    /* 
    This does not produce any error, why ???? 
    void add_attribute(string name, string value){ 
     (*ptr_nav)[0] = name; 
     (*ptr_nav)[1] = value; 
     sz++; 
     ptr_nav++; 
    } 
    */ 

private: 
    string tagname; 
    string **attrib_list, **ptr_nav; 
    int sz, t_sz; 
}; 

int main() { 
    Tag t("tag1", 2); 
    t.add_attribute("value1", "1"); //runtime error 
    t.add_attribute("value2", "2"); //runtime error 
    return 0; 
} 
+1

ポインタについて学んでいないなら、私は強く 'vector'と' unique_ptr'を使うことをお勧めします – Arunmu

答えて

0

をコンパイルするhackerrankオンラインIDEを使用し、attrib_listは二回インクリメントし、現在、元new[] -allocated配列の終わりを越え指しています。それ自体は問題ではありません。

しかし、その後、あなたのTagインスタンスは、スコープの外に出るそのデストラクタが実行され、もちろん、未定義の挙動を示す今-無効attrib_listポインタ、上attrib_list[i]にアクセスしようとします。

当面の問題とは無関係の

t_sz, sz = 0;は、2つの変数(あなたが信じているように見えるよう)に、だけszに0を割り当てることはありません。あなたの好きなC++リファレンスのコンマ演算子について読んでください。いずれにしても、最初に行う必要はありません(2つのポインタをnullptrに設定する必要はありません)。それらはいずれにせよ破壊されようとしています。その時点での値は関係ありません。

+0

Yah right、haha ...どうしたのですか?P –

関連する問題