-1

This is the code I am using to connect to my LDAPserver. While compiling it doesn't show any errors, but in running the JVM is crashing. What is the problem with this code?

JNIEXPORT void JNICALL Java_Login_uInsert(JNIEnv *env, jclass mycls, jstring id, jstring fname, jstring lname), JNI generated header line.

{
    LDAP *ldap = NULL;
    const int version = LDAP_VERSION3;
    const char* host = "localhost";

    ldap = ldap_init(host,10389);
    int result = ldap_set_option(ldap,LDAP_OPT_PROTOCOL_VERSION,&version);

    const char *sid = env->GetStringUTFChars(id, NULL);
    const char *sfname = env->GetStringUTFChars(fname, NULL);

    LDAPMod a1,a2,a3;

    char *dn="uid=1913015,ou=users,ou=system";

    char *id_values;
    strcpy(id_values,sid);
    a1.mod_op=LDAP_MOD_ADD;
    a1.mod_type="uid";
    a1.mod_values=&id_values;

    char *cn_values;
    strcpy(cn_values,sfname);
    a2.mod_op=LDAP_MOD_ADD;
    a2.mod_type="cn";
    a2.mod_values=&cn_values;

    char *oc_values[] = {"inetOrgPerson", NULL};
    a3.mod_op = LDAP_MOD_ADD;
    a3.mod_type = "objectClass";
    a3.mod_values = oc_values;

    LDAPMod *entry[4];
    entry[0]=&a1;
    entry[1]=&a2;
    entry[2]=&a3;
    entry[3]=NULL;

    ldap_add(ldap,dn,entry);
    ldap_unbind(ldap);
}
Botje
  • 21,384
  • 3
  • 27
  • 38
Rahul RR
  • 1
  • 1
  • Why? You can communicate with LDAP from Java directly with JNDI. No need for any JNI code here. Don't make things any more complex than they need to be. – user207421 May 22 '22 at 10:27
  • Your issue has nothing to do with C. You're calling strcpy with an uninitialized pointer as destination. – Botje May 23 '22 at 11:08
  • 1
    As a more applicable solution: your attempts to strcpy those strings into separate variables add nothing of value. Just do `a1.mod_values=&sid` and `a2.mod_values=&sfname;`. Don't forget to call `env->ReleaseStringUTFChars` at the end of your function! – Botje May 23 '22 at 11:11
  • @Botje How does that have nothing to do with C? – user207421 May 23 '22 at 23:53
  • Thanks for all helpful comments. I rectified the issue…the problem is in the improper memory management in code. Thanks mates. – Rahul RR May 24 '22 at 02:32
  • @user207421 I meant "JNI". D'oh! – Botje May 24 '22 at 11:40
  • If you had written in this in JNDI the memory error could never have happened in the first place. – user207421 May 25 '22 at 00:06

0 Answers0