Search code examples
c++linuxdllg++shared-libraries

The problem with the explicit dynamic library


I wrote a dynamic library in C++ random.so, which contains a rand_int function that generates numbers in a given range. I connected my library implicitly (via include "../shared/rand.h") and everything worked, but when explicitly connected I get the error "fish: Job 1, './example' terminated by signal SIGSEGV (Address boundary error)", below is the code of my program and library.

// example.cpp
#include <cstdio>
#include <dlfcn.h>

int main(int argc, char *argv[]) {
  void *ext_library;
  int (*rand)(int, int);

  ext_library = dlopen("/home/nikita/Libraries/shared/librandom.so", RTLD_LAZY);
  if (!ext_library) {
    fprintf(stderr, "dlopen() error: %s\n", dlerror());
    return 1;
  }

  rand = (int (*)(int, int))dlsym(ext_library, argv[1]);

  printf("%d", (*rand)(0, 10));

  dlclose(ext_library);
  return 0;
}
// random.cpp
#include <random>
int rand_int(int min, int max) {
  std::random_device rd;
  std::mt19937 gen(rd());
  std::uniform_int_distribution<int> dist(min, max);
  return dist(gen);
}
// random.h
int rand_int(int min, int max);

random.cpp and random.h are in my "shred" folder, and example.cpp located in the "lb" folder, 2 these folders are in the same directory. example.cpp I was compile using this command:

g++ example.cpp -o example -ldl

Then I started it with the command ./example. Then I ran it with the command ./example, after which I got an error "fish: Job 1, './example' terminated by signal SIGSEGV (Address boundary error)"

I tried changing the compiler to clang, but it didn't help, example.cpp it is easy to assemble, by any compiler, but always gives the same error.


Solution

  • You are calling ./example without parameters so argv[1] is NULL.