c++ - push_back() 时出现段错误

标签 c++ stl

我在 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.
}

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

关于c++ - push_back() 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27215414/

相关文章:

c++ - 处理一长串单词。是否可以同时分批处理?

c++ - 强制无线网卡只扫描一个 channel (以编程方式)

c++ - 使用C++创建一个sqlite3表

c++ - 如何将一张 map 的内容 append 到另一张 map ?

c++ - socket编程,什么是FD和SD

c++ - C++ 指针不能改变它们的原始值

C++ 基于链表的树结构。理智地在列表之间复制节点

c++ - 初始化 std::byte 容器的正确方法

c++ - 将 STL 算法与 Qt 容器结合使用

c++ - vector 迭代器不可取消引用?