2016-03-25 110 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