Неполадки при поиске причины ошибки сегментации - PullRequest
0 голосов
/ 02 апреля 2019

Код продолжает давать ошибку сегментации (ядро сброшено) ошибка

Я чувствую, что что-то не так с 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;



};

1 Ответ

0 голосов
/ 03 апреля 2019

Есть несколько вещей, которые не так с вашим классом:

  1. Я не вижу ничего, что обеспечивает, что std::vector<ParticlePtr> также не обеспечивает (правильно).
  2. Выне предоставили оператор присваивания и таким образом нарушили правило 3 .
  3. Ваш конструктор копирования неверен и не инициализирует ни одного из ваших участников.
  4. Ваш *Метод 1013 * реализует индексирование на основе 1, которое, вероятно, смущает всех.

Весьма вероятно, что проблема 2 или 3, описанная выше, является основной причиной вашего сбоя.

Но проблемы 1 должно быть достаточно, чтобы выбросить этот код и заменить его на std::vector.

...