iOS上的mmap有时会返回0xffffffff

时间:2013-03-26 19:32:18

标签: ios c mmap

我尝试使用以下代码在iOS设备上使用mmap

struct stat s;
    int status;
    size_t size;
    int fd;

    fd = open ([dataFile cStringUsingEncoding:NSUTF8StringEncoding], O_RDONLY);
    fcntl( fd, F_NOCACHE );
    status = fstat (fd, & s);
    if (status < 0)
    {
        // error handling
    }
    size = s.st_size;
    FuncFileLog(@"%@", @"before read");
    off_t offset = 0;
    char* data = (char *) mmap(NULL, size, PROT_READ, MAP_SHARED, fd, offset);

    char *pch;
    int lastPosInString = 0;

    pch=strchr(data,'\n');

long lineCounter = 0;

    while (pch != NULL)
    {
        size_t lineLength = 0;

        int posInString = pch - data + 1;
        lineLength = posInString - lastPosInString;

        char *out = calloc(lineLength, sizeof(char));

        memcpy(out, data + lastPosInString, lineLength);
        out[lineLength - 1] = '\0';

        if (lineCounter > 0)
        {
           // do something
        }

        lastPosInString = posInString;
        pch=strchr(pch+1,'\n');

        lineCounter = lineCounter + 1;
    }

    munmap((void *)data, size);
    close(fd);

它有效,但有时当我读取大约3.5 mb的文件时我没有任何理由得到EXC_BAD_ACCESS,因为我的mmap数据指针是0xffffffff,这是我认为的错误。 它似乎只发生在模拟器中。

我明白了 errno:12 Cannot allocate memory 目前只在模拟器中使用

上的守卫malloc,后卫边缘,涂鸦和僵尸

1 个答案:

答案 0 :(得分:2)

我建议您阅读mmap的手册页(打开Terminal.app并输入man mmap

RETURN VALUES
     Upon successful completion, mmap() returns a pointer to the mapped region.  
     Otherwise, a value of MAP_FAILED is returned and errno is set to indicate 
     the error.

还有一节描述了可能设置的errno