代码不断给出分段错误(核心掉落)错误
我觉得getNumberParticles()有点问题;就像当我刚刚返回0作为函数定义时一样,没有错误,但是如果我返回除0以外的任何内容,则会出现错误
如果您能告诉我使用gdb 它是一个具有多个主文件的多文件程序 我不确定如何像这样调试它
particleList.cpp
ParticleList::ParticleList() {
numParticles = 0;
particles[500] = {};
}
// ParticleList::ParticleList(int rows, int cols){
// numParticles = 0;
// particles[rows * cols * 4] = {};
// }
ParticleList::ParticleList(const ParticleList& obj){
}
// Clean-up the particle list
ParticleList::~ParticleList() {
for(int i = 0 ; i < 500 ; i++){
delete particles[i];
}
}
// Number of particles in the ParticleList
int ParticleList::getNumberParticles() {
numParticles = 0;
for(int i = 0 ; i < 500 ; i++){
if(particles[i] != nullptr){
numParticles++;
}
}
return this->numParticles;
}
// Get a pointer to the i-th particle in the list
ParticlePtr ParticleList::get(int i) {
return particles[i-1];
}
// Add a particle (as a pointer) to the list
// This class now has control over the pointer
// And should delete the pointer if the particle is removed from the list
void ParticleList::add_back(ParticlePtr particle) {
int quantity = getNumberParticles();
particles[quantity]= particle;
}
// Remove all particles from the list
void ParticleList::clear() {
for(int i = 0 ; i < 500 ; i++){
particles[i]= nullptr;
}
}
ParticleList.h
#ifndef COSC_ASS_ONE_PARTICLE_LIST
#define COSC_ASS_ONE_PARTICLE_LIST
#include "Particle.h"
#include "Types.h"
class ParticleList {
public:
/* */
/* DO NOT MOFIFY ANY CODE IN THIS SECTION */
/* */
// Create a New Empty List
ParticleList();
ParticleList(const ParticleList& obj); //Copy Construcor
// Clean-up the particle list
~ParticleList();
// Number of particles in the ParticleList
int getNumberParticles();
// Get a pointer to the i-th particle in the list
ParticlePtr get(int i);
// Add a particle (as a pointer) to the list
// This class now has control over the pointer
// And should delete the pointer if the particle is removed from the list
void add_back(ParticlePtr particle);
// Remove all particles from the list
// Don't forget to clean-up the memory!
void clear();
/* */
/* YOU MAY ADD YOUR MODIFICATIONS HERE */
/* */
ParticleList(int rows, int cols);
/* This is a suggestion of what you could use. */
/* You can change this code. */
private:
// particle* particles[300]
//Array of pointers to particle objects
ParticlePtr particles[500];
int numParticles;
};
答案 0 :(得分:0)
您的班级有一些问题:
std::vector<ParticlePtr>
也没有(正确地)提供的任何内容。get
方法实现了基于1的索引,这很可能会使所有人感到困惑。上述问题2或3很可能是导致崩溃的根本原因。
但是问题1应该足以丢弃此代码,并用std::vector
代替。