Search code examples
c++reinterpret-cast

Segfault converting pointers with reinterpret_cast


In the following C++ code, I am attempting to load a function from a shared library.

void* tmp = dlsym(dl_lib, symbol);
_fun = reinterpret_cast<plot_sample_fun*>(tmp);

However, the reinterpret_cast segfaults when converting the pointers. What is wrong here?

Edit:

To provide further context,

typedef void plot_sample_fun( const void *, double **, char ***, size_t *);

class Foo {
    void bar(); // Loads _fun as above.

    plot_sample_fun* _fun;
};

Solution

  • The pointer physically is just an integer variable that contains some address.

    The reinterpret_cast is just a trick to make compiler believe that the pointer is of certain type.

    In the code sample above the only possibility of segfault either first line but the author says second, or the second line and the reason is _fun is some kind of dangled reference so it writes to an incorrect memory location.

    After the author updated us on the pointer type it is clearer that the correct code should look like:

    typedef void (plot_sample_fun*)( const void *, double **, char ***, size_t *);
    

    Also the assignment:

    _fun = reinterpret_cast<plot_sample_fun>(tmp);
    

    And the class member declaration should not have asterisk *

    plot_sample_fun _fun;
    

    And if that does not help then we wonder if the instance of class that contains _fun is allocated correctly and not released yet.