2016-03-25 108 views
0

不知道为什么我对这段特定的代码行出现分段错误,我知道当您尝试访问您无法访问的内存部分但是我无法访问时出现此错误弄清楚什么是错的。分割故障核心转储C++

我想改变场景,并通过把矢量中的对象的功能,我得到分割错误(核心倾倒) ,这只发生在我推球体和平面,当我评论这2行出它的作品,但它不会渲染球体当然.. 任何想法? 它也适用,如果我删除“if语句” 谢谢。

vector < Source * > lightSource; 
vector < Object * > sceneObjects; 

while (!glfwWindowShouldClose(window)) { 
    if (firstScene) { 
     Sphere sphereScene(sphere, .825, green_ref); 
     Plane planeScene(plane[0][0], plane[0][1], -1, maroon); 
     Light lightScene(light, whiteLight); 

     ////////////this is what is causing problem i think////////////////// 
     sceneObjects.push_back(dynamic_cast < Object * > (& sphereScene)); 
     sceneObjects.push_back(dynamic_cast < Object * > (& planeScene)); 
     ///////////////////////////////////////////////////////////////////// 

     lightSource.push_back(dynamic_cast < Source * > (& lightScene)); 
     for (int i = 0; i < 4; i++) { 
      sceneObjects.push_back(new Triangle(pyramidCoord[i], Blue)); 
     } 
     for (int i = 0; i < 2; i++) { 
      sceneObjects.push_back(new Triangle(ceiling[i], White)); 
     } 
     for (int i = 0; i < 2; i++) { 
      sceneObjects.push_back(new Triangle(wallG[i], Green)); 
     } 
     for (int i = 0; i < 2; i++) { 
      sceneObjects.push_back(new Triangle(wallR[i], Red)); 
     } 
     for (int i = 0; i < 2; i++) { 
      sceneObjects.push_back(new Triangle(floor1[i], White)); 
     } 
    } 
+0

这是难以阅读的代码片段 - 似乎缺少括号(S)。如果缩进是正确的,那么Sphere,Plane和Light对象的生命周期将在if块之后结束。但悬停的指针现在未定义的内存存储在sceneObjects列表中,并可能在以后访问(和崩溃)。为什么不使用像Triangle这样的新产品? – Anders

+0

好点我把它改成了这个sceneObjects.push_back(新球体(sphere,.825,green_ref)); sceneObjects.push_back(new Sphere(plane [0] [0],plane [0] [1],-1,m aroon)); lightSource.push_back(new Light(light,whiteLight));不是我得到不同的错误,但它不再分段错误 – blank

+0

耶!下一次重要的是发布最小完整可验证示例(MVCE)http://stackoverflow.com/help/mcve,所以我们不必猜测。现在,到你的下一个问题;-) – Anders

回答

0

您正在将本地基于栈的变量的地址推送到一个容器中,后面您将动态分配的对象添加到该容器中。在这些变量被销毁后,您可能会引用本地(sphereScene,planeScene)。清理所有分配给Triangles的内存也是一个问题,因为你无法删除当地人的内存。

假设ObjectSphere等的基础,您不应该需要dynamic_cast来存储指针。

0

这个固定

sceneObjects.push_back(new Sphere(sphere,.825,green_ref)); 
sceneObjects.push_back(new Sphere(plane[0][0],plane[0][1], -1, maroon)); 
lightSource.push_back(new Light(light,whiteLight)); 

,但现在我得到另一个错误

错误:调用“球::球(GLM :: VEC 3 &,GLM :: VEC 3 &没有匹配功能,int,Color &)' sceneObjects.push_back(new Sphere(plane [0] [0],plane [0] [1],-1,maroon));

这是我的函数定义看起来像在sphere.h

#ifndef SPHERE 
#define SPHERE 


class Sphere : public Object { 
    vec3 center; 
    double radius; 
    Color color; 

public: 
    Sphere(); 
    Sphere(vec3, double, Color); 
}; 


Sphere::Sphere() 
{ 
    vec3 center(0,0,0); 
    radius=1.0; 
    color= Color(0.5,0.5,0.5,0); 
} 

Sphere::Sphere(vec3 centerV, double radiusV, Color colorV) 
    { 
     center=centerV; 
     radius=radiusV; 
     color=colorV; 
    } 


#endif // SPHERE 
+0

函数原型有引用('glm :: vec3&'),而函数定义不('vec3')。 – 1201ProgramAlarm

+0

没关系,我推了两次Sphere而不是推飞机。考虑这个问题关闭谢谢大家。 – blank