Error while using strcat() in JNI
David Nugent
davidn at datalinktech.com.au
Thu Jun 4 01:13:39 UTC 2009
On Thu, 04 Jun 2009 07:38:43 +1000, Deshmukh, Pramod
<Pramod_Deshmukh at 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
More information about the freebsd-java
mailing list