分段故障核心转储C++

Segmentation Fault core dumped C++

本文关键字:C++ 转储 核心 故障 分段      更新时间:2023-10-16

不确定我为什么会在这一行代码中出现分段错误,我知道当你试图访问你无法访问的内存部分时会出现错误,但我无法找出问题所在。

我试图在场景之间切换,通过将推动对象的函数放入向量中,我得到了分段错误(核心转储),只有当我推动球体和平面时才会发生这种情况,当我评论这两条线时,它可以工作,但它当然不会渲染球体。。有什么想法吗?如果我删除"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&aamp;,int,Color&)"时没有匹配的函数sceneObjects.push_back(新球体(平面[0][0],平面[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