为什么这个 c++ 程序会给出 seg 错误
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;
相关文章:
- C++ - 将元素按升序插入数组的 SEG 错误
- 为什么我在使用 istream 迭代器时会出现 seg 错误?
- 字符串上的合并排序上的 Seg 错误
- 导致 Seg 错误的 SingleLinkedList 的析构函数
- g++ 9.2.1 (Linux) 会导致 seg 错误,但 Windows 上的代码块不会
- 函数抛出seg错误,我不知道为什么
- Microsoft Visual Studio 2019交叉编译CMake库 - 有效,但存在SEG错误
- 由于相同的文件名/类名存在于不同的SO中而导致的SEG错误
- 尝试访问 3D 矢量中的元素时出现 Seg 错误
- 垫子对象数组太大会导致 Seg 错误
- 为什么push_back成矢量<矢量<int>>导致 seg 错误?
- 在向量中存储字符串存在 SEG 错误
- 更改本地类名时出现 seg 错误
- 使用 ->GetString( " ") 时出现 Seg 错误,它位于单独的类中
- 将字符数组转换为 std::string 以传递到 std::bitset seg 错误
- 字符和 int 连接何时会导致 seg 错误?
- 静态数组溢出堆栈(seg 错误 11)仅在类定义内部时,否则不会..?
- .EOF 在读取文件时导致 Seg 错误:FIXXED
- 在 qt5 中使用 QSharedPointer 时出现 Seg 错误
- 为什么我的 if 语句会出现 seg 错误?