簡體   English   中英

為什么這個C ++程序給段錯誤

[英]Why this c++ program giving seg fault

為什么這個程序給分割錯誤。 我正在為20個字符串分配內存。 (默認情況下也是20)。 並設置並嘗試訪問第20個元素。

#include <iostream>
using namespace std;


class myarray
{
  private:
    string *items;
  public:

    myarray (int size=20)
    {
      items = new string[size];
    }

    ~myarray()
    {
      delete items;
    }

    string& operator[] (const int index)
    {
      return items[index];
    }
    /* 
    void setvalue (int index, string value)
    {
      items[index] = value;
    }

    string getvalue (int index)
    { 
      return items[index];
    }
    */

};


int main()
{
  myarray m1(20);
  myarray m2;
  m1[19] = "test ion";
  cout << m1[19];
  //m1.setvalue (2, "Devesh ");
  //m1.setvalue (8, "Vivek ");
  //cout << m1.getvalue(19);
  return 0;
}

如果像使用new string[size]一樣分配數組,則需要使用delete[] items;

使用delete[]代替delete

經驗法則是:

  • 如果使用new分配了內存,請使用delete釋放它。
  • 如果您使用new[]分配了內存,請使用delete[]釋放它。

將構造函數更改為:

items = new string[size]();

和破壞者:

delete[] items;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM