0

我有代码:

unsigned char *myArray = new unsigned char[40000];

char pixelInfo[3];
int c = 0;
while(!reader.eof()) //reader is a ifstream open to a BMP file
{
    reader.read(pixelInfo, 3);
    myArray[c] = (unsigned char)pixelInfo[0];
    myArray[c + 1] = (unsigned char)pixelInfo[1];
    myArray[c + 2] = (unsigned char)pixelInfo[2];
    c += 3;
}
reader.close();

delete[] myArray; //I get HEAP CORRUPTION here

经过一些测试,我发现它是由 while 循环中的强制转换引起的,如果我使用有符号的 char myArray我没有收到错误,但我必须在其余代码中使用无符号字符。将 pixelInfo 转换为 unsigned char 也会产生相同的错误。

有什么解决办法吗?

4

3 回答 3

1

这是你应该做的:

reader.read((char*)myArray, myArrayLength); /* note, that isn't (sizeof myArray) */

if (!reader) { /* report error */ }

如果循环内部正在进行处理,那么

int c = 0;
while (c + 2 < myArraySize) //reader is a ifstream open to a BMP file
{
    reader.read(pixelInfo, 3);
    myArray[c] = (unsigned char)pixelInfo[0];
    myArray[c + 1] = (unsigned char)pixelInfo[1];
    myArray[c + 2] = (unsigned char)pixelInfo[2];
    c += 3;
}

在你读完之后尝试阅读不是问题——你会在数组的其余部分中得到垃圾,但你可以在最后处理它。

假设您的数组足够大以容纳整个文件会导致缓冲区损坏。涉及带有精心设计的不正确元数据的图像文件的缓冲区溢出攻击是众所周知的。

不要依赖于适合计算的缓冲区大小的整个文件内容。

于 2012-12-28T21:25:17.700 回答
0

reader.eof()只会告诉您前一次读取是否到达文件末尾,这会导致您的最终迭代写入数组末尾。您想要的是检查当前读取是否到达文件末尾。while将循环更改为:

while(reader.read(pixelInfo, 3)) //reader is a ifstream open to a BMP file
{
  // ...
}
于 2012-12-28T21:21:43.097 回答
0

请注意,您一次读取 3 个字节。如果字节总数不能被 3 整除(不是 3 的倍数),那么实际上只有一部分 pixelInfo 数组会填充正确的数据,这可能会导致程序出错。您可以尝试以下未测试的代码。

while(!reader.eof()) //reader is a ifstream open to a BMP file
{
   reader.read(pixelInfo, 3);
   for (int i = 0; i < reader.gcount(); i++) {
       myArray[c+i] = pixelInfo[i];
   }
   c += 3;
}

Your code does follow the documentation on cplusplus.com very well since eof bit will be set after an incomplete read so this code will terminate after your last read however, as I mentioned before the likely cause of your issue is the fact that you are assigning likely junk data to the heap since pixelInfo[x] might not necessarily be set if 3 bytes were not read.

于 2012-12-28T21:38:23.377 回答