尝试使用 setter 时出现双重释放或损坏 (fasttop) 错误
Double free or corruption (fasttop) error when trying to use setter
我根据教科书创建了一个包含 setter
和 getters
的基本 class 对象。代码工作正常,但是当我尝试将 name
中的数据从 Square
更改为 Circle
时,我得到 error : double free or corruption (fasttop)
.
有人能告诉我这里发生了什么吗?这是由于某种内存分配错误吗?
下面是一个可重现的代码:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
class Shape
{
protected:
string name;
bool contains = false;
public:
Shape(string name, bool contains)
{
setName(name);
setContains(contains);
}
string getName();
bool getContains();
string setName(string name);
bool setContains(bool contains);
};
string Shape :: setName(string inputName)
{
name = inputName;
}
bool Shape :: setContains(bool inputContains)
{
contains = inputContains;
}
string Shape :: getName()
{
return name;
}
bool Shape :: getContains()
{
return contains;
}
int main()
{
Shape object1("Square", true);
cout << "Testing" << endl;
cout << object1.getName() << endl;
cout << object1.getContains() << endl;
object1.setName("Circle");
cout << object1.getName() << endl;
return 0;
}
编辑:
有意思,当运行OnlineGDB中没有object1.setName("Circle");
和cout << object1.getName() << endl;
的代码会报segmentation fault错误。解决这个问题的方法是什么?
您的 setName
和 setContains
函数没有任何 return
语句,而它们的 return 类型不是 void
。
因此,执行这些函数会调用 未定义的行为.
N3337 6.6.3 return 语句表示:
Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.
要解决此问题,您应该执行之一:
- 将函数
setName
和 setContains
的 return 类型更改为 void
。
- 在函数中添加具有适当 return 值的
return
语句。
我根据教科书创建了一个包含 setter
和 getters
的基本 class 对象。代码工作正常,但是当我尝试将 name
中的数据从 Square
更改为 Circle
时,我得到 error : double free or corruption (fasttop)
.
有人能告诉我这里发生了什么吗?这是由于某种内存分配错误吗?
下面是一个可重现的代码:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
class Shape
{
protected:
string name;
bool contains = false;
public:
Shape(string name, bool contains)
{
setName(name);
setContains(contains);
}
string getName();
bool getContains();
string setName(string name);
bool setContains(bool contains);
};
string Shape :: setName(string inputName)
{
name = inputName;
}
bool Shape :: setContains(bool inputContains)
{
contains = inputContains;
}
string Shape :: getName()
{
return name;
}
bool Shape :: getContains()
{
return contains;
}
int main()
{
Shape object1("Square", true);
cout << "Testing" << endl;
cout << object1.getName() << endl;
cout << object1.getContains() << endl;
object1.setName("Circle");
cout << object1.getName() << endl;
return 0;
}
编辑:
有意思,当运行OnlineGDB中没有object1.setName("Circle");
和cout << object1.getName() << endl;
的代码会报segmentation fault错误。解决这个问题的方法是什么?
您的 setName
和 setContains
函数没有任何 return
语句,而它们的 return 类型不是 void
。
因此,执行这些函数会调用 未定义的行为.
N3337 6.6.3 return 语句表示:
Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.
要解决此问题,您应该执行之一:
- 将函数
setName
和setContains
的 return 类型更改为void
。 - 在函数中添加具有适当 return 值的
return
语句。