我的写函数中的地址错误

时间:2014-12-03 01:45:35

标签: c++ mmap

我必须对这个小任务进行编码,但却找不到我的错误。它应该只读取文件中的一些数据,然后以相反的顺序将其复制到另一个文件中。第一部分似乎有效,但是while-part在每次使用write函数时都会给出“Bad Address”。我很感激每一个想法!

#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;
}

1 个答案:

答案 0 :(得分:0)

你要自己踢! (当我终于发现问题时,我踢了自己!)

这一行:

    offset =- map_size;

应该是:

    offset -= map_size;

另见What does =+ mean in C?

comments问题的Andrew Medico之一观察到clang立即识别出问题 - 而且确实存在:

$ clang -O3 -g -std=c++11 -Wall -Wextra -Werror badadd.cpp -o badadd
    badadd.cpp:65:16: error: use of unary operator that may be intended as compound assignment (-=)
          [-Werror]
            offset =- map_size;

G ++(GCC)4.9.1(在Mac OS X 10.9上本地构建,在10.10.1上运行)具有相同的编译器选项并不能识别问题。

JFTR:我发现问题的方法很困难(使用print语句跟踪offset的值),并且在找到并发布答案后才阅读Andrew的评论。< / EM>