NIFs Segmentation Fault without creating erl_crash.dump however code is working fine when ran normallly without NIFs.

I am working on integrating a Third Party C++ api in Elixir using NIFs. Here is the code sample that is shared and is working fine when I run it like a binary.

class Client: public AbstractThirdPartyClient {
  public:
    int ConnectionSuccess(int status) {
       return status;
    }
};

Client *client = new Client;
ThirdPartyControl *control;

int main () {
  control = new ThirdPartyControl(client, "fully/qualified/path/to/some/config/file");
  return 0;
}

But when I am trying to introduce NIFs converting to a dynamic lib (.so) file, NIF loading fails with seg fault and since ThirdPartyControl class implementation is hidden from me, I am having a hard time figuring out why this is failing.

typedef struct {
 Client *client;
 ThirdPartyControl *control;
} node;

ERL_NIF_TERM setup(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) {
  return enif_make_atom(env, "ok");
}

static ErlNifFunc nif_funcs[] = {{"setup", 0, setup}};

int load(ErlNifEnv* caller_env, void** priv_data, ERL_NIF_TERM load_info) {
  try {
    node *r = (node *)malloc(sizeof(node));
    r->client = new Client;
    /* this line causes seg fault don't know why */
    r->control = new ThirdPartyControl(r->client, (char *)NULL, (char *)"fully/qualified/path/to/some/config/file");
    *priv_data = r;
  } catch (exception e) {
    return 1;
  }
  return 0;
}

int upgrade(ErlNifEnv* caller_env, void** priv_data, void **old_priv_data, ERL_NIF_TERM load_info) {
  return 0;
}

ERL_NIF_INIT(Elixir.Vendor.Middleware, nif_funcs, load, NULL, upgrade, NULL);
1 Like