简体   繁体   中英

Why this c++ program giving seg fault

Why this program giving segmentation fault. I am allocating the memory for 20 strings. (by default is also 20). and setting and trying to access 20th element.

#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 .

Rule of thumb is:

  • If you have allocated memory with new , free it with delete .
  • If you have allocated memory with new[] , free it with delete[] .

Change constructor to:

items = new string[size]();

And destructor to:

delete[] items;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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