D
D
Danil Vaskevich2021-07-17 15:47:08
C++ / C#
Danil Vaskevich, 2021-07-17 15:47:08

How to solve the access violation error when reading from an address?

Hello, I encountered a runtime error that says the following:

Вызвано исключение по адресу 0x007C3AD9 в home_oop_inheritance_virtual_metod_spd_animal.exe: 0xC0000005: нарушение прав доступа при чтении по адресу 0x00000000.

The code in which the error appears:
void printAll(){
        for (size_t i = 0; i < zoo.size() + 1; i++)
        {
            zoo[i]->show();// ошибку выдает здесь
            cout << endl;
        }
    }


Parent class code:
class Animal
{
protected:
    string name = "NoName";
    size_t age = 1;
public:
    Animal(const string& name, const size_t& age)
        :name(name), age(age) {}
    Animal() = default;

    virtual void sound() const = 0;
    virtual void type() const = 0;
    virtual void show() const = 0;

    string getName() {
        return this->name;
    }
    size_t getAge() {
        return this->age;
    }
    
    void setName(const string& newName) {
        if (newName != "")
        {
            name = newName;
            return;
        }
        return;
    }
    void setAge(const size_t newAge) {
        if (newAge >= 0)
        {
            age = newAge;
            return;
        }
        return;
    }
};


This is the code that I'm just learning about inheritance in C++, so don't judge too harshly if there are mistakes. I will be grateful for any help.

PS I decided to change the output method a bit.
for (size_t i = 0; i < zoo.size() - 1; i++)
        {
            zoo[i]->type();
            cout << " Name: " << zoo[i]->getName() << " Age: " << zoo[i]->getAge() << " ";
            zoo[i]->sound();

            cout << endl;
        }


PS(2) in my case zoo is a vector

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Armenian Radio, 2021-07-17
@DaniVffgf

Well, a guaranteed flight beyond the array boundary is here. i < zoo.size() + 1
What does +1 do here?

W
Wataru, 2021-07-17
@wataru

Run in debugger. It will stop at the line with the error. Check the values ​​of all variables (zoo - vector size? i - what is equal to?)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question