Possible Duplicate:
Getting segmentation fault SIGSEGV in memcpy after mmap
I'm using mmap() in my cpp code to map a large size area (100,000,000 bytes ~ 100MB).
From man mmap I understand that I can only know whether it succeeded or not, I cannot know how much size it succeeded to map.
In my case, I could read that area iteratively with a buffer of 8192 bytes, but after I read ~24MB I get SIGSEGV - means that mmap didn't map the entire area successfully?
I'm reading by a memcpy function to copy from the mapped area to my buffer on the heap. (I see the same behavior also when the buffer is on the stack).
How can I know if it mapped the entire area or not? And if it mapped the entire area then why do I get the SIGSEGV after around 24MB of bytes read?
Thanks!
int * addr = reinterpret_cast<int *>(mmap(NULL, length , PROT_READ, flags , fd, 0));
// ...
int * initaddr = addr;
char buffer[jbuffer_size];
void *ret_val = buffer;
int read_length = length;
while(ret_val == buffer || read_length<jbuffer_size) {
ret_val = memcpy(buffer, addr,jbuffer_size);
addr+=jbuffer_size;
read_length -= jbuffer_size;
}
So, your termination condition looks wrong: you decrement read_length
and loop until it is less than buffer_size
.
Also, you're incrementing addr
by buffer_size
integers (it is an int*
), not bytes. So, you're advancing addr
4 times too fast.
BTW, in other code: lseek
takes and returns an off_t
, not a size_t
.
Edit: most of these bugs are pointed out in the other question already, so I'm not sure this one adds anything.