什么是内存访问冲突? [英] What's causing the memory access violation?
问题描述
我遇到内存访问冲突
Swarm swarm;
while(true){
const Particle * const pParticles = swarm.getParticles();
for (int i = 0; i < swarm.N; i++)
{
Particle particle = pParticles[i];
int x = (particle.x+) * (screen.width/2);
int y = (particle.y+1) * (screen.height/2);
screen.setPixel(x,y,255,255,255);
}
screen.update();
if(!screen.processEvents())
break;
}
在 pParticles [i]
。指针只是访问其分配的内存块(在构造函数中分配),我不会在代码中的任何地方篡改指针。这里是Swarm类:
at pParticles[i]
. The pointer is just accessing its allocated memory block (allocated in the constructor) and I'm not tampering with the pointer anywhere in the code. here's the Swarm class:
// Sawrm.h
class Swarm
{
public:
const static int N = 6000;
private:
Particle * particles;
public:
const Particle * const getParticles() { return particles; };
Swarm::Swarm(void)
{
particles = new Particle[Swarm::N];
}
Swarm::~Swarm(void)
{
delete [] particles;
}
};
// Swarm.cpp
Swarm::Swarm(void)
{
particles = new Particle[Swarm::N];
}
Swarm::~Swarm(void)
{
delete [] particles;
}
如果N大于5000(说6000)我运行它几次,异常。但是如果我再次增加N,我再次得到异常等等。
if N is greater than 5000 (say 6000) I get the exception. I run it a couple times and the exception goes. but if I increase N again I get the exception again and so on. What's going on here?
这里是Particle类,只有两个 double
变量 x,y
:
Here's the Particle class which has nothing but two double
variables x,y
:
Particle::Particle(void)
{
x = (1.0*rand())/RAND_MAX ;
y = (1.0*rand())/RAND_MAX ;
}
Particle::~Particle(void)
{
}
推荐答案
我通过使字段N非静态,非const并初始化它在构造函数中修复了问题。不知道为什么这个工作。如果任何人都能提供证明为什么这样做的理由,我会很高兴。
I fixed the problem by making the field N non-static, non-const and initializing it in the constructor instead. Not sure why this works. I'll be happy if anyone can provide a justification as to why this works.
这篇关于什么是内存访问冲突?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!