为什么这个 c++ 程序会给出 seg 错误

Why this c++ program giving seg fault

本文关键字:seg 错误 程序 c++ 为什么      更新时间:2023-10-16

为什么这个程序给出分段错误。我正在为 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;