سؤال

I have the following section of code:

char*
Sender::PrepareData(char* filename, unsigned long long int bytesToTransfer)
{
    int fd, pagesize;
    char *data;

    ifstream file(filename, ios::binary | ios::ate);
    int size = file.tellg();
    cout << "File Size: " << size << endl;

    if(size < bytesToTransfer)
        {cout << "File smaller than specified number of bytes {" << bytesToTransfer << "} to transfer -- Exiting!\n"; exit(1);}

    fd = open(filename, O_RDONLY);
    if (fd==NULL) {fputs ("File error",stderr); exit (1);}

    cout << "File Open: " << filename << endl;

    pagesize = getpagesize();
    cout << "Pagesize: " << pagesize << endl;

    data = static_cast<char*>(mmap((caddr_t)0, bytesToTransfer, PROT_READ, MAP_SHARED, fd, 0));
    if (*data == -1) {fputs ("Memory error",stderr); exit (2);}

    return data;
}

This seemingly works fine for text and .deb files - however, when trying with a ~3MB image file (.jpg), I get memory errors:

File Size: 3333840
File Open: t1.jpg
Pagesize: 4096
Memory error[Inferior 1 (process 3293) exited with code 02]

Am I using mmap() wrong? I'm trying to write a simple wrapper that will take any type of file and return a char* containing the specified number of bytes.

هل كانت مفيدة؟

المحلول

You should be checking just data == -1 (or, even better, MAP_FAILED) and not *data == -1 (dereferencing via * is wrong here).

The reason your code fails is because the first byte of every JPEG file is FF in hex or -1 in signed decimal.

For more detail on JPEG, Google for "JPEG file format." For example, search for "SOI" on this page.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top