c++ - 故障查找分段故障原因
问题描述
代码不断给出分段错误(核心掉线)错误
我觉得 getNumberParticles() 有问题;当我只返回 0 作为函数定义时,没有错误,但是如果我返回除 0 之外的任何其他内容,则会出现错误
另外,如果您告诉我使用 gdb,它是一个带有一个主文件的多文件程序,我不确定如何像那样调试它
粒子列表.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;
}
}
粒子列表.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;
};
解决方案
你的课有几个问题:
- 我没有看到它提供的任何东西
std::vector<ParticlePtr>
也没有提供(正确)。 - 您没有提供赋值运算符,因此违反了3 的规则。
- 您的复制构造函数不正确,并且没有初始化您的任何成员。
- 您的
get
方法实现了基于 1 的索引,这很可能使所有人感到困惑。
上面的问题 2 或 3 很可能是您崩溃的根本原因。
但是问题 1 应该足以丢弃此代码并将其替换为std::vector
.
推荐阅读
- angular - 角度输出操作不适用于事件触发
- java - activiti 7 候选用户任务
- laravel - Unauthorized response with valid token
- javascript - 自API返回的时间以来,如何再次运行时钟?
- sql-server - 检查存储过程的结果中是否存在值
- android - 更改 RxJava2 链中的数据类型
- javascript - 在 azure 函数(js)中,异步/等待调用后的 POST 请求不起作用
- django - Django AES 加密:如何在保存用户上传的文件之前对其进行加密?
- sequelize.js - 在续集迁移中写入没有换行符的 Stdout
- java - 无法从 Spring Cloud 配置服务器接收值