Exception thrown at 0x7A2A93B6 (vcruntime140d.dll) in file.exe: 0xC0000005: Access violation reading location 0xCDCDCDCD

0

I'm having issues while trying to get the typeid of an array. When I type typeid(*ptr[0]).name(), it works perfectly fine. but as soon as I change the 0 to a variable in a loop it gives me this error please help me!

#include "Cellphone.h"
#include "Electronic_device.h"
#include "Laptop.h"
#include "Smartwatch.h"
#include <vector>
#include <typeinfo>

int main()
{
    string name;
    int i = 0;
    Electronic_device** ptr = new Electronic_device*[100];
    Cellphone c1("Samsung", 1023, "black", 250.00, 1);
    Smartwatch s1("IBM", 10, "red", 350.00, 2);
    Laptop l1("HP", 102, "black", 1250.00, 16, true);
    ptr[0] = &c1;
    ptr[1] = &s1;
    ptr[2] = &l1;
    ptr[0]->print();
    
    for (i = 0; i < sizeof(ptr); i++)
    {
        if (typeid(*ptr[i]) == typeid(Cellphone))
        {
            cout << "Cellphone" << endl;
        }
        if (typeid(*ptr[i]) == typeid(Smartwatch))
        {
            cout << "Smartwatch" << endl;
        }
        if (typeid(*ptr[i]) == typeid(Laptop))
        {
            cout << "Laptop" << endl;
        }
    }
    
    ((Cellphone *)ptr[0])->printCellphone();
}
c++

1 Answer

0

You are reading uninitialized memory. First, initialize your array to zero, so that all pointers are null:

Electronic_device** ptr = new Electronic_device*[100]();

Secondly, you must check that the value is not null before you dereference the pointer (call *ptr[i]), for example:

for (i = 0; i < 100 && ptr[i] != nullptr; i++)

If you use dynamic_cast to check the derived class, then you don't have to dereference the pointer at all in your example:

if (dynamic_cast<Cellphone*>(ptr[i]) != nullptr) {
    cout << "Cellphone" << endl;
}
answered on Stack Overflow Apr 8, 2021 by vll

User contributions licensed under CC BY-SA 3.0