1

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;
};
ehuang
  • 811
  • 1
  • 8
  • 17
  • 1
    You may read http://stackoverflow.com/questions/310451/should-i-use-static-cast-or-reinterpret-cast-when-casting-a-void-to-whatever – chrizke Nov 20 '14 at 19:02
  • 3
    What is _fun? That reinterpret_cast does not do the exception by itself. It only forces compiler to believe that the pointer is of some type. But that segfault is about storing the pointer in some other memory location. – Alexander V Nov 20 '14 at 19:06
  • 1
    Is it really the `reinterpret_cast` that segfaults, not a later use of the pointer? And why aren't you checking that it's not null? – Mike Seymour Nov 20 '14 at 19:09
  • 2
    There is no chance that the cast is causing the segfault, as it doesn't actually do anything. – molbdnilo Nov 20 '14 at 19:24
  • AlexanderVX is correct, storing values into the class member _fun is causing the segfaults. – ehuang Nov 20 '14 at 23:51
  • Even something as simple as this->_fun = NULL segfaults. – ehuang Nov 20 '14 at 23:52

2 Answers2

2

The reinterpret_cast itself can't segfault, since it only changes the type of the expression for the compiler. It gets compiled away and doesn't do anything at runtime (unlike for example dynamic_cast).

What is failing is your use of the pointer later in the program.

Unlike static_cast, but like const_cast, the reinterpret_cast expression does not compile to any CPU instructions

I recommend compiling the program with debugging turned on (-g with gcc/clang) and then running it in a debugger, to see what is actually failing.

Jakub Arnold
  • 85,596
  • 89
  • 230
  • 327
2

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.

Alexander V
  • 8,351
  • 4
  • 38
  • 47