Home > Net >  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

Time:09-11

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;
}

CodePudding user response:

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:

#include <new>

auto derived_ptr = new(void_ptr)Derived;
  • Related