访问非空指针时出现段故障
Segfault when accessing non-null pointer?
该代码在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)
,看看这个断言是否成立。
PrivProcessParticles
的n
的起始值是多少?它会不会碰巧和head
一样呢?
注:此外,出于好奇,您用来决定是否执行删除的逻辑似乎表明,实际上是关于节点n
的决定(您检查n->life <= 0
和n->immortal
)。然后你继续删除head
,而不是n
…这是故意的吗?
P.P.S.一个小问题:你在AddParticle
中做了过多的n->next = NULL
初始化。
相关文章:
- Python & C-C++ 扩展模块案例段故障
- 中断;导致段故障
- 带指针的调用函数会导致段故障
- 由于变量范围导致的段故障
- 为什么通过shared_from_this()会导致段故障
- 简单的C++字符数组加密功能 - 段故障
- std::vector的函数push_back中的堰段故障
- 在openCV中将cvPoint[][]转换为cvPoint**时出现段故障
- 模板变量分配段故障11
- CIN 一个非常大的 int 数组,段故障 11
- C++段故障错误
- 段故障 -> 在标准::basic_ostream<字符中,标准::char_traits<char>
- C++中的二叉树段故障
- 调试执行工作正常,但正常的一段故障
- c++:几乎相同的输入,但第二次调用显示段故障
- 段故障。地址0x0不是堆叠的、恶意的或(最近)释放的
- 使用矢量引起的段故障
- 使用arm-linux- gnuabi -g++ -o时出现段故障,不使用-o也不会出现问题
- 为什么会出现以下段故障
- 在类文件和缓冲区中查找段故障