Cannot call a pointer to a function that returns a pointer

I am stuck with a strange problem. I have two files ac and bc as follows: bc:

#include <stdlib.h>

int *foo() {
  int *x;
  x = (int *) malloc(sizeof(int));
  *x = 4;
  return x;
}

I am compiling bc in b.so using gcc: $ gcc -o b.so -shared -fpic

ac:

#include <stdio.h>
#include <dlfcn.h>

int main() {
  void *hdl;
  hdl = dlopen("./b.so", RTLD_LAZY);
  int *((*fn)(void));
  int *x;
  x = (*fn)();
  fn = dlsym(hdl, "foo");
  printf("%d", *x);
}

I compile ac using gcc:

$ gcc -fpic -ldl ac

Now that I have run it:

$. / a.out segmentation error

Where am I mistaken? This works when a function in bc does not return a pointer.

And furthermore, I tried to check for errors using dlerror (), but it does not report anything.

+3
source share
4 answers

fn, . foo, - , , undefined.

+6

.

x = (*fn)();, foo b.c.

.

  int *x;
  fn = dlsym(hdl, "foo");
  x = fn();
  printf("%d", *x);

.

EDIT:

dlopen, dlsym man- .

+4

, , , :

 x = (*fn)();
fn = dlsym(hdl, "foo");
+3

:

x = (*fn)();
fn = dlsym(hdl, "foo");
+3

Source: https://habr.com/ru/post/1758328/


All Articles