I have to code this little task and can´t find my mistake. It should just read some data from a file and copy it in opposite order into another one. The first part seems to work, but the while-part gives me "Bad Address" for every time the write function is used. I´m grateful for every idea!
#include <iostream>
#include <cerrno>
#include <fcntl.h>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#define TRY(cmd,msg) {                                          \
    if ((cmd) < 0) {                                            \
      std::cerr << (msg) << ": " << strerror(errno) << std::endl;       \
    }                                                                   \
  }
int main(int argc, char *argv[]){
    int fd_in, fd_out, rest;
    off_t map_size, offset, length;
    char * addr;    
    struct stat sb;
    if (argc != 3) {
        std::cerr << "Usage: kopfstand in out" << std::endl;
        return -1;
    }
    if ((fd_in = open(argv[1],O_RDONLY)) == -1){
        perror("open");
        return -1;
    }
    if ((fd_out = open(argv[2],O_WRONLY|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR)) == -1){
        close(fd_in);
        perror("open");
        return -1;
    }
    fstat(fd_in, &sb);
    length = sb.st_size;
    map_size = sysconf(_SC_PAGESIZE);
    rest = length % map_size;
    offset = length -rest;
    if(rest != 0){
        addr = (char*)mmap(NULL, rest, PROT_READ, MAP_PRIVATE, fd_in, offset);
        if(addr == MAP_FAILED){
            perror("Error mmaping the File");
        }
        for (int off = rest-1;  off >= 0; --off){
            TRY(write(fd_out, addr+off, 1),"write");
        }
        if(munmap((char*)addr, rest)== -1){
            perror("munmap");
        }
    }
    while(offset > 0){
        offset =- map_size;
        addr = (char*)mmap(NULL, map_size, PROT_READ, MAP_SHARED, fd_in, offset);
        if(addr == MAP_FAILED){
            perror("Error mmaping the File");
        }
        for(int off = map_size-1; off >= 0; --off){
           TRY(write(fd_out, addr+off, 1),"write");
        }   
        if(munmap((char*)addr, map_size) == -1){
           perror("munmap");
        }   
    }
    close(fd_in);
    close(fd_out);
    return 0;
}