返回指针的C ++方法:分段错误

时间:2014-06-29 17:56:10

标签: c++ pointers reference segmentation-fault dereference

下面的代码给了我一个分段错误,我已经尝试了很多不同的东西但是无法理解为什么它不起作用。我对C ++很陌生,所以如果这个问题可能有点容易,我很抱歉;)这是我的代码:

 class Line2D
 {
 public:
   Point2D punkt; 
   double dx, dy; 
   void set_values(Point2D p, double d1, double d2);
   Point2D* getIntersectionPoint(Line2D& line2);
 };

 void Line2D::set_values(Point2D p, double d1, double d2)
 {
   punkt = p;
   dx = d1;
   dy = d2;
 }

 Point2D* Line2D::getIntersectionPoint(Line2D& line2)
 {
   double a, b;
   Point2D* intersec; 
   double det = dx*line2.dy - dy*line2.dx;
   if(det == 0)
   {
     return NULL;
   }
   else
   {
     double c1 = line2.punkt.k1 - punkt.k1;
     double c2 = line2.punkt.k2 - punkt.k2;
     a = (line2.dy*c1 - line2.dx*c2)/det;
     b = (dx*c2 - dy*c2)/det;
   }
   intersec->set_values(a,b);
   return intersec;
 }


 int main()
 {
   //...
   Line2D l1;
   Line2D l2;
   l1.set_values(p3,6,3);
   Point2D p11;
   p11.set_values(1,6);
   l2.set_values(p11,4,0);
   Point2D* intersec;
   intersec = l1.getIntersectionPoint(l2);
 }

1 个答案:

答案 0 :(得分:5)

你有

Point2D* intersec; 

未初始化为指向任何有效对象。

为它分配内存并在此之后使用指针。

Point2D* Line2D::getIntersectionPoint(Line2D& line2)
{
   double a, b;

   // Initialize the pointer to NULL so
   // that it will be easy to detect when it
   // points to valid object.
   Point2D* intersec = NULL;

   double det = dx*line2.dy - dy*line2.dx;
   if(det == 0)
   {
     return NULL;
   }
   else
   {
     double c1 = line2.punkt.k1 - punkt.k1;
     double c2 = line2.punkt.k2 - punkt.k2;
     a = (line2.dy*c1 - line2.dx*c2)/det;
     b = (dx*c2 - dy*c2)/det;
   }

   // Allocate memory for a Point2D
   intersec = new Point2D;

   intersec->set_values(a,b);
   return intersec;
}

<强>更新

确保在main中删除了返回的对象。

int main()
{
   //...
   Line2D l1;
   Line2D l2;
   l1.set_values(p3,6,3);
   Point2D p11;
   p11.set_values(1,6);
   l2.set_values(p11,4,0);
   Point2D* intersec;
   intersec = l1.getIntersectionPoint(l2);

   // Use intersec
   // ...
   // ...

   // Delete intersec before the end of main.
   delete intersec;
}

std::shared_ptr完成后,您可以使用main自动删除对象。

int main()
{
   //...
   Line2D l1;
   Line2D l2;
   l1.set_values(p3,6,3);
   Point2D p11;
   p11.set_values(1,6);
   l2.set_values(p11,4,0);
   std::shared_ptr<Point2D> intersec = l1.getIntersectionPoint(l2);

   // Use intersec
   // ...
   // ...
}