JiaWei Lee Ответов: 2

Программа получила сигнал SIGSEGV, ошибка сегментации


Как решить проблему с памятью?
(gdb) run                                                                              
Starting program: /home/a.out                                                          
                                                                                       
Program received signal SIGSEGV, Segmentation fault.                                   
0x0000000000400e32 in OldMcDonald::OldMcDonald (this=0x7fffffffeb50)                   
    at main.cpp:39                                                                     
39              _farm[0] = new Animal("Cow","Moo");                                    
(gdb)


Что я уже пробовал:

#include <iostream>

using namespace std;


class Animal {
private:
    string _name;
    string _sound;
public:
Animal(string name, string sound){
    _name = name;
    _sound = sound;
}

    string getName(){
        return _name;
    }
    
    string getSound(){
        return _sound;
    }
};

class OldMcDonald {
private:
    Animal** _farm; // Old McDonald had a farm (still has now)
    const int _size; // Fixed farm size
public:
    OldMcDonald():_size(3) {
        _farm[0] = new Animal("Cow","Moo");
        _farm[1] = new Animal("Dog","Woof");
        _farm[2] = new Animal("Duck","Quack");
        
    }
    ~OldMcDonald() {
        for(int i = 0; i < _size; i++){
            delete _farm[i];
        }
        delete[]_farm;
    }
    
    void sing() {
        for (int i=0; i<_size; i++) {
            cout << "Old McDonald had a farm, E-I-E-I-O\n";
            cout << "And on his farm he had a"" " <<_farm[i]->getName()<<", E-I-E-I-O\n";
            cout << "With a " <<_farm[i]->getSound()<<" "<<_farm[i]->getSound()<<" here and a " <<_farm[i]->getSound()<<" "<<_farm[i]->getSound()<<" there\n";
            cout << _farm[i]->getSound()<<" " "here"" " <<_farm[i]->getSound()<<" " "there, everywhere"" " <<_farm[i]->getSound()<<" "<<_farm[i]->getSound()<<"\n";
            cout << "Old McDonald had a farm, E-I-E-I-O\n\n";
        }
    }
    
};

2 Ответов

Рейтинг:
2

Richard MacCutchan

Вы заявили: _farm в качестве Animal** но никогда ничего не выделял указателю.


Рейтинг:
0

CPallini

В дополнение к Ричард's решение, Пожалуйста, обратите внимание на C++ Стандартная библиотека предоставляет лучшие альтернативы контейнерам do-it-yourself (например, путаница с выделением памяти). Попробуй

#include <iostream>
#include <vector>

using namespace std;

class Animal
{
private:
    string _name;
    string _sound;
public:
    Animal(string name, string sound): _name(name), _sound(sound){}

    string getName() const { return _name; }

    string getSound() const { return _sound; }
};

class OldMcDonald
{
private:
    vector <Animal> _farm;
public:
    OldMcDonald()
    {
        _farm.push_back( Animal("Cow","Moo"));
        _farm.push_back( Animal("Dog","Woof"));
        _farm.push_back( Animal("Duck","Quack"));
    }

    void sing() const
    {
        for ( const auto & a : _farm)
        {
            string sound = a.getSound();
            cout << "Old McDonald had a farm, E-I-E-I-O\n";
            cout << "And on his farm he had a"" " << a.getName() <<", E-I-E-I-O\n";
            cout << "With a " << sound << " " << sound << " here and a " << sound << " "<< sound <<" there\n";
            cout << sound<<" " "here"" " << sound <<" " "there, everywhere"" " << sound << " " << sound << "\n";
            cout << "Old McDonald had a farm, E-I-E-I-O\n\n";
        }
    }
};


int main()
{
  OldMcDonald omd;
  omd.sing();
}