簡體   English   中英

分段故障核心轉儲C ++

[英]Segmentation Fault core dumped C++

不知道為什么我在此特定的代碼行中出現分段錯誤,我知道當您嘗試訪問您無權訪問的一部分內存時會收到該錯誤,但我無法弄清楚出了什么問題。

我試圖在場景之間進行切換,並通過將推動對象的功能放入向量中,我得到了細分錯誤(核心轉儲),只有當我按球體和平面時,才會發生這種情況,當我注釋掉這兩行時,它不會呈現當然的范圍..任何想法? 如果我刪除“ 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));
        }
    }

您正在將基於堆棧的本地變量的地址推入到容器中,然后將動態分配的對象添加到該容器中。 這些變量被銷毀后,您可能正在引用局部變量( sphereSceneplaneScene )。 為所有分配的三角形清理內存也是一個問題,因為您不能刪除本地人的內存。

假設ObjectSphere等的基礎,則不需要dynamic_cast存儲指針。

這個解決了

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));

但是現在我又遇到了另一個錯誤

錯誤:沒有匹配函數可調用'Sphere :: Sphere(glm :: vec3&,glm :: vec3&,int,Color&)'sceneObjects.push_back(new Sphere(plane [0] [0],plane [0] [1 ],-1,栗色));

這就是我的函數定義在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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM