无法调用指向函数的指针返回指针

Nil*_*esh 3 c pointers function-pointers

我遇到了一个奇怪的问题.我有两个文件ac和bc如下:bc:

#include <stdlib.h>

int *foo() {
  int *x;
  x = (int *) malloc(sizeof(int));
  *x = 4;
  return x;
}
Run Code Online (Sandbox Code Playgroud)

我使用gcc编译bc到b.so:$ 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);
}
Run Code Online (Sandbox Code Playgroud)

我用gcc编译ac:

$ gcc -fpic -ldl ac

现在当我运行它:

$ ./a.out分段错误

我哪里错了?这在bc中的函数不返回指针时有效.

而且,我尝试使用dlerror()检查错误,但它没有报告.

Bet*_*eta 6

通过检查,您fn在初始化之前使用.它还没有指出foo,它还没有特别指出任何东西,我怀疑结果行为是未定义的.