[英]Why do I get memory errors when mmap()'ing a JPG file?
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: 这似乎适用于文本和.deb文件 - 但是,当尝试使用~3MB图像文件(.jpg)时,我会收到内存错误:
File Size: 3333840
File Open: t1.jpg
Pagesize: 4096
Memory error[Inferior 1 (process 3293) exited with code 02]
Am I using mmap()
wrong? 我使用
mmap()
错了吗? 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. 我正在尝试编写一个简单的包装器,它将获取任何类型的文件并返回包含指定字节数的char *。
You should be checking just data == -1
(or, even better, MAP_FAILED
) and not *data == -1
(dereferencing via *
is wrong here). 您应该只检查
data == -1
(或者更好, MAP_FAILED
)而不是 *data == -1
(通过*
解除引用是错误的)。
The reason your code fails is because the first byte of every JPEG file is FF
in hex or -1 in signed decimal. 您的代码失败的原因是因为每个JPEG文件的第一个字节是十六进制的
FF
或带符号十进制的-1。
For more detail on JPEG, Google for "JPEG file format." 有关JPEG的更多详细信息,请参阅Google的“JPEG文件格式”。 For example, search for "SOI" on this page .
例如,在此页面上搜索“SOI”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.