在 c++ 中操作向量时的分割错误
Segmentation fault when operating a vector in c++
我正在尝试学习 c++,我想用一个简单的程序将 X 实例的向量初始化为类成员,但我遇到了分段错误......你能帮忙吗?
#include <iostream>
#include <vector>
class X {
int _x;
public:
X(int i) { _x = i; }
void print() { std::cout << this->_x << std::endl; }
void xAdd() { _x++; }
};
class Y {
std::vector<X*> _x;
public:
Y(int size) : _x(size) {
for (int i = 0; i < size; ++i) _x.push_back(new X(1));
}
void printAll() {
for(unsigned int i = 0; i < _x.size()-1; i++) {
_x[i]->print();
}
}
};
int main(){
Y *y = new Y(5);
y->printAll();
return 0;
}
你用size
空指针初始化_x
;然后你把另一个size
有效的指针推到它上面。然后printAll
尝试取消引用这些空指针。
删除初始化器(可能添加_x.reserve(size);
以最小化分配);或者将循环体更改为_x[i] = new X(1);
作为一般说明,你使用new
太多了。矢量没有理由包含指针而不是对象,也没有理由让y
是动态的而不是自动的。
您有 2 个内存泄漏。 除非必要,否则不要使用new
。
在不需要初始化时,可以使用循环进行初始化。
设置向量的初始大小(以及初始值),然后执行push_back
。 因此,前 N
值是默认构造的(和 NULL
)。
您的printAll
函数将打印除最后一个元素之外的所有元素。
class X
{
private:
int _x;
public:
X(int i) { _x = i; }
void print() { std::cout << _x << std::endl; } // this-> is not needed
void xAdd() { _x++; }
};
class Y
{
private:
std::vector<X> _x; // no need to store pointers, store the object itself
public:
Y(int size) : _x(size, X(1)) // use the fill version of the constructor
{ }
// simple way to print (there are other ways to do the same thing)
void printAll()
{
std::for_each(_x.begin(), _x.end(), [](const X& x)
{
x.print();
});
}
};
int main()
{
Y y(5); // no need for heap allocation
y.printAll();
return 0;
}
你的问题出在Y
类的构造函数中:
class Y {
std::vector<X*> _x;
public:
Y(int size) : _x(size) { // initializing the vector with size elements all set to nullptr
for (int i = 0; i < size; ++i) _x.push_back(new X(1)); // pushing back size pointers to actual instances of X
}
void printAll() {
for(unsigned int i = 0; i < _x.size()-1; i++) { // iterating over the first size items of the vector which are the nullptrs and derefencing them.
_x[i]->print();
}
}
};
您应该考虑将其作为一种std::vector<X>
来摆脱您目前必须处理的所有指针。
相关文章:
- C++映射分割错误(核心转储)
- 由cin中的字符串中未捕获空白引起的分割错误
- 删除映射和分割错误中的一个过去结束元素
- 在指向函数中读取变量时出现分割错误
- 在链表中的第 n 位插入显示分割错误
- 较高值 n 的分割错误(例如 n=999997)
- 尝试通过memcpy复制大尺寸浮点向量时的分割错误
- 分割错误:向量中的擦除功能
- 向量向量的分割错误
- 我在C++中编写了一个方法来打印树类的预序,但它显示了分割错误
- C ++分割错误,为什么使用"long long"我没有得到答案?
- 在尝试使用递归查找集合子集的总数时,我遇到了分割错误
- 分割错误 11:尝试使用 cin 输入 B[1] 时
- 集合布局上的 Qt 分割错误
- 高达20亿的筛子会产生分割错误
- 对向量使用推回函数时的分割错误
- 绘制精灵会导致分割错误
- 将矢量的整数内容打印为字符串会导致分割错误
- 分割错误:使用向量时为 11 c++
- 结构的分割错误错误