Skip site navigation (1)Skip section navigation (2)
Date:      Thu, 04 Jun 2009 10:44:18 +1000
From:      "David Nugent" <davidn@datalinktech.com.au>
To:        "Deshmukh, Pramod" <Pramod_Deshmukh@securecomputing.com>, freebsd-java@freebsd.org
Subject:   Re: Error while using strcat() in JNI
Message-ID:  <op.uuy5n4yw5gjz8p@activate-sjc0.adobe.com>
In-Reply-To: <5CF2BB5045ED7D44B69F3E63642D693207E63FCF@ICE.scur.com>
References:  <5CF2BB5045ED7D44B69F3E63642D693207E63FCF@ICE.scur.com>

next in thread | previous in thread | raw e-mail | index | archive | help
On Thu, 04 Jun 2009 07:38:43 +1000, Deshmukh, Pramod  
<Pramod_Deshmukh@securecomputing.com> wrote:

> Below is the c program which is called by java. Java passed string  
> object to this method which is converted to char *. When I print using  
> printf()
> function it prints the string (char *), but strcat() does not like char  
> *.


Your diagnosis is incorrect. This issue has nothing to do with JNI as  
such, the crash is caused by a bug in your code.

> Attached is the .h file the same. Please help me. Also I have attached  
> the .log file
[..]
> JNIEXPORT jstring JNICALL Java_nativetest_sayHello(JNIEnv *env, jobject  
> thisobject, jstring p_data, jstring p_salt)
> {
>     printf("Inside C program \n");
>     printf("=================================\n");
>     char *cmdOpenSsl;
>     jboolean iscopy;
>     char* cDesc = strdup((*env)->GetStringUTFChars(env, p_data,  
> &iscopy));
>     printf("cDesc ==  %s ", cDesc);
>     cmdOpenSsl = "echo -n ";
>     strcat(cmdOpenSsl, cDesc);

You're assigning a non-writable address to the variable cmdOpenSsl and  
then trying to concatenate something to it. Make sure you a) can write to  
where you are strcat()ing to, and b) there is sufficient room there.

Try something like:

   static const char *echo = "echo -n ";
   ..
   cmdOpenSsl = malloc(strlen(echo) + strlen(cDesc) + 1);
   strcpy(cmdOpenSsl, echo);
   strcat(cmdOpenSsl, cDesc);

Personally I've found it wise to avoid use of malloc (and indirect use via  
strdup) in JNI code however. It can be done of course, but you have to be  
careful to not introduce memory leaks. I would prefer alloca() or use C++  
locals.

Regards,
David



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?op.uuy5n4yw5gjz8p>