push_back() 时分段错误

segmentation fault while push_back()

本文关键字:分段 错误 back push      更新时间:2023-10-16

我在push_back()函数中运行代码时遇到分段错误,我的程序如下。

程序:

#include<iostream>
#include <vector>
using namespace std;
class Point
{
  private:
    int x, y;
    int * p;
  public:
    Point(int x1, int y1)  {
      x = x1; y = y1;
      *p = 1;
    }
    Point(const Point & p2) {
      x = p2.x;
      y = p2.y;
      *p = 1;
    }
};
int main()
{
  Point p1(10, 15);
  Point p2 = p1;
  vector<Point> vec;
  for (int i=0; i<10; i++)
  {
    vec.push_back(p2);
  }
}

有人可以给出上述程序中分段错误的原因吗????有人可以给出上述程序中分段错误的原因吗????

Point(int x1, int y1)  {
  x = x1; y = y1;
  *p = 1;            <<< allocate memory for this pointer first.
}

您正在取消引用未初始化的指针。

如果你想

直接修改它们的值,我建议公开x和y;这比让getter和setter来完成这项工作要好。同时,我建议这样修改你的代码:

int *p = new int;

这样做将为指针分配内存,然后可以为其分配值。只是出于好奇,指针是干什么用的?