Question

I'm working on Android development. I have a native method with a pointer parameter:

int writeData(unsigned char* readbuff, int length)

I want to pass value to the address readbuff point to. I did it like this:

int readData(unsigned char* readbuff, int length){//unsigned
   *readbuff = 'a';
   return 0;
    }

But it failed with:

Fatal signal 11 (SIGSEGV) at 0x74e9a36e (code=2), thread 14078 (Thread-1916)

My question is how can I change the value in readbuff? I have searched a lot, but still can't get the answer. Please help me! Thank you very very much!

EDIT: Here is my new code:

int readData(unsigned char* readbuff){
   JNIEnv *env;
   unsigned char* tmpbuff = "abc";
   if(readbuff==NULL||length < 4)
        __android_log_print(ANDROID_LOG_DEBUG, "error", "readbuff is null");
   else
       memcpy ( readbuff, tmpbuff, 3 );
}

Now the method is called like this:

void test(){
   unsigned char* readbuff = "this is jni"; 
       readData(readbuff);
}

But I still got same error... Please help!

Partially Solved! I tried a lot and finally get the app run. I just change the test() like this:

void test(){
   unsigned char readbuff[11] = "this is jni"; //edit here
       readData(readbuff);
}

But I'm not good in C, who can tell me why readbuff[11] work but *readbuff not? Thanks again and again!

Was it helpful?

Solution

The difference between

unsigned char* readbuff = "this is jni";

and

unsigned char readbuff[11] = "this is jni";

is the first one points to a string literal, which must not be modified. The second one is a local char array containing the same string, but the char array may be freely modified.

However, be aware that the array is too small by one character. It is missing space for the final NUL byte. If you want to have an array exactly as long as needed, you can say

unsigned char readbuff[] = "this is jni";

Update:

To do the same dynamically, you can do

void test(){
    unsigned char* readbuff = malloc(256);
    readData(readbuff);
}

But you must not forget to free the memory eventually.

OTHER TIPS

You have to use memcpy instead of the assignment of = 'a' (assuming your talking about C, you used a lot of tags there ^^)

void * memcpy ( void * destination, const void * source, size_t num );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top