Re: Error while using strcat() in JNI

[ Available lists | Index of freebsd-java | Month of Jun 2009 | Week of 4 Jun 2009 | Raw email | View thread | Wrap long lines | Reply | Tag ]
From
David Nugent <davidn@datalinktech.com.au>
Date
4 Jun 2009 01:13:39
Subject
Re: Error while using strcat() in JNI
Message-ID
op.uuy5n4yw5gjz8p@activate-sjc0.adobe.com

In reply to
References to

[ Hide this part ]
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

Elapsed time: 0.157 seconds