Skip to content Skip to sidebar Skip to footer

Getting Segmentation Fault Sigsegv In Memcpy After Mmap

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 really need to cal

Solution 1:

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.

Solution 2:

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.

Solution 3:

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.

Solution 4:

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).

Post a Comment for "Getting Segmentation Fault Sigsegv In Memcpy After Mmap"