简体   繁体   English

为什么这个C ++程序给段错误

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

Why this program giving segmentation fault. 为什么这个程序给分割错误。 I am allocating the memory for 20 strings. 我正在为20个字符串分配内存。 (by default is also 20). (默认情况下也是20)。 and setting and trying to access 20th element. 并设置并尝试访问第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;

Use delete[] instead of delete . 使用delete[]代替delete

Rule of thumb is: 经验法则是:

  • If you have allocated memory with new , free it with delete . 如果使用new分配了内存,请使用delete释放它。
  • If you have allocated memory with new[] , free it with delete[] . 如果您使用new[]分配了内存,请使用delete[]释放它。

Change constructor to: 将构造函数更改为:

items = new string[size]();

And destructor to: 和破坏者:

delete[] items;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM