Getting segmentation fault SIGSEGV in memcpy after mmap

前端 未结 4 1801
既然无缘
既然无缘 2021-01-23 16:50

I wrote a simple Android native function that get a filename and some more arguments and read the file by mmapping (mmap) it\'s memory.

Because it\'s mmap, I don\'t real

相关标签:
4条回答
  • 2021-01-23 17:09

    This loop never terminates because ret_val always equals buffer

    void *ret_val = buffer;
    int read_length = length;
    while(ret_val == buffer || read_length<jbuffer_size) {
        /*****GETTING SIGSEGV SOMWHERE HERE IN THE WHILE************/
        ret_val = memcpy(buffer, addr,jbuffer_size);
        addr+=jbuffer_size;
        read_length -= jbuffer_size;
    }
    

    memcpy always returns it's first argument, so ret_val never changes.

    0 讨论(0)
  • 2021-01-23 17:15

    The while loop is infinite:

    while(ret_val == buffer || read_length<jbuffer_size) {
        ret_val = memcpy(buffer, addr,jbuffer_size);
        addr+=jbuffer_size;
        read_length -= jbuffer_size;
    }
    

    as memcpy() always returns the desintation buffer so ret_val == buffer will always be true (and is therefore useless as part of the terminating condition). This means that addr is being incremented by jbuffer_size bytes on every iteration of the loop and is passed to memcpy(), resuting in accessing invalid memory.

    0 讨论(0)
  • 2021-01-23 17:22

    The condition in while(ret_val == buffer || read_length<jbuffer_size) is wrong. ret_val == buffer will always be true, and if read_length<jbuffer_size is true when the loop is reached, it will always remain true because read_length is only ever reduced (well, until it underflows INT_MIN).

    0 讨论(0)
  • 2021-01-23 17:29

    There is a big problem here:

        addr+=jbuffer_size;
    

    You're bumping addr by sizeof(int) * jbuffer_size bytes whereas you just want to increment it by jbuffer_size bytes.

    My guess is sizeof(int) is 4 on your system, hence you crash at around 25% of the way through your loop, because you're incrementing addr by a factor of 4x too much on each iteration.

    0 讨论(0)
提交回复
热议问题