Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calling overrided method on Derived class casted from void ptr causes segmentation fault

Calling overrided method on Derived class casted from void ptr causes segmentation fault.
It doesn’t if derive from concrete (non abstract) class.

#include <cstdio>

struct Base{
    virtual void base_method() = 0;
};

struct Derived : Base{
    int x;
    void own_method(){
        printf("own %d", x);
    }
    void base_method() override{
        printf("base %d", x);
    }
};

int main() {
    auto * char_ptr = new char[500];
    void * void_ptr = char_ptr;
    auto derived_ptr = (Derived*)void_ptr;
    derived_ptr->x = 15;
    derived_ptr->own_method();
//    derived_ptr->base_method(); SEGMENTATION ERROR IF UNCOMMENT
    return 0;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You didn’t run the constructor of Derived, so your code has UB. In case of ItaniumABI, your virtual table is not populated and thus you’re likely jumping to an undefined address. If you’d like to use the char array / void* as the memory for Derived, you can do placement new:

auto derived_ptr = new(void_ptr)Derived;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading