访问非空指针时出现段故障

Segfault when accessing non-null pointer?

本文关键字:故障 段故障 空指针 访问      更新时间:2023-10-16

该代码在Linux环境下运行良好,但在Windows中,它在程序启动后5-10秒崩溃。调试器指向n->fired = true;作为问题?

void ParticleSystem::PrivProcessParticles(pNodePtr n, double frameTime)
{
      while(n != NULL) {
        n->fired = true;
        if(!n->immortal)
            n->life -= frameTime; //Decrement life
        n->particle.ApplyAccel2D(frameTime);
        /* Since the oldest particles will always be on
           top of the queue, if life is zero, dequeue! */
        if(n->life <= 0) {
            if(head != NULL && !n->immortal) {
                pNodePtr curr;
                curr = head;
                head = head->next;
                delete curr;
            }
        }
        n = n->next;
    }
}
分配:

void ParticleSystem::AddParticle(double lifeIn, double x, double y, double angle,
                                 double size, double force, bool immortalIn)
{
    //Increment particle count
    count++;
    //Allocate
    pNodePtr n = new particleNode;
    //Initialize
    n->particle.CreateQuad(size);
    n->particle.SetTexture(texture);
    n->particle.SetPos2D(x, y);
    n->particle.SetRot2D(angle);
    n->particle.SetTopSpeed(topSpeed);
    n->particle.SetVelocity(force);
    n->life = lifeIn;
    n->immortal=immortalIn;
    n->fired = false;
    n->next = NULL;
    //Place
    if (head == NULL) 
    {
        head = n;
        tail = n;
        n->next = NULL;
    } else {
        tail->next = n;
        tail = n;
    }
}
节点:

struct particleNode {
        Quad particle;
        double life;
        bool fired;
        bool immortal;
        particleNode* next;
};

发布的信息不够。然而,这里有一个潜在的问题来源。

当你的PrivProcessParticles函数在n上执行迭代时,它可以决定删除列表中的head元素。但是有没有可能在它决定删除head的那一刻,n实际上和head是一样的?如果是这样,删除head会使n变成一个悬空指针,这将导致n = n->next的灾难性后果。

delete curr之前添加assert(curr != n),看看这个断言是否成立。

无论如何,调用者传递给PrivProcessParticlesn的起始值是多少?它会不会碰巧和head一样呢?

注:此外,出于好奇,您用来决定是否执行删除的逻辑似乎表明,实际上是关于节点n的决定(您检查n->life <= 0n->immortal)。然后你继续删除head,而不是n…这是故意的吗?

P.P.S.一个小问题:你在AddParticle中做了过多的n->next = NULL初始化。