Search code examples
csegmentation-faultposixpointer-arithmetic

Write in a for-loop breaking program (unexpectedly)


I am trying to write values of allocated memory to file using POSIX open, write, close functions with a early defined block size (io_block). So when I do something like this

#define memory_size (310*1024*1024)
#define start_address (void*) 0x190573A0
#define file_size (147*1024*1024)
#define io_block 138

int* ptr = mmap(start_address, memory_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, 0, 0);
int* thread_ptr_start = ptr;
int* thread_ptr_end = ptr + file_size;
int* loop_address;
for (loop_address = thread_ptr_start; loop_address < thread_ptr_end; loop_address += io_block) {
    write(output_file, loop_address, io_block);
}

I didn't get a normal result, because some memory can not be read (BAD ACCESS), but when I do this (deleting cycle)

write(output_file, thread_ptr_start, thread_ptr_end - thread_ptr_start);

While debugging I saw, that BAD ACCESS happened in the middle of the range [thread_ptr_start, thread_ptr_end) everything become normal.

How can I get the first example working normally?


Solution

  • The pointers are "int *". So when you increment them (in the loop), they increment by steps of sizeof(int) (and not 1 byte !). At each iteration of the loop, loop_address = loop_address + (io_block * sizeof(int)). That would explain why you may go too far in the memory zone.

    Moreover, the call to write(...io_block), only writes io_block bytes (not io_block * sizeof(int)).