我开发了一个小程序,它运行良好,直到我对代码的一些不相关部分进行了非常小的更改。从那时起,程序将抛出一个未处理的 win32 异常,并且 Microsoft Visual Studio 及时调试器启动。
我正在使用代码块,我的编译器是 gcc 编译器。令人沮丧的是,如果我选择使用 gdb 从代码块进行调试,程序运行良好。这对我来说没有意义。
由于我无法使用 gdb 进行调试以查看问题所在(因为它在 Debug模式下运行良好),因此我将 printfs 放在各处以找出所有问题的根源。我隔离了一个功能,但它没有意义。
bool FileReader::readBitmap(int fileNum)
{
char check;
int dataOffset;
int dataSize;
string fileName;
//used for quick int to string conversion
std::ostringstream stringstream;
stringstream<<fileNum;
string fileNumber = stringstream.str();
fileName = "img"+fileNumber+".bmp";
ifstream stream(fileName.c_str(),ios::in|ios::binary);
stream.read(&check,1);
//checking if it is a bitmap file
if(check != 'B')
return false;
stream.read(&check,1);
if(check != 'M')
return false;
stream.seekg(BMPBPP);
stream.read(&check,1);
//if it is not a monochrome bitmap
if(((int)check) != 1)
return false;//quit
//get the dataoffset
stream.seekg(DATAOFFSET);
stream.read(&check,1);
dataOffset = (int)check;
//get the data size in bytes
stream.seekg(DATASIZEINBYTES);
stream.read(&check,1);
dataSize = (int)check;
//if this is the first image we read
if(firstImageRead)
{
//allocate the image buffer
imgBuffer = (char*) malloc(dataSize);
//and make sure it does not get re-allocated
firstImageRead = false;
}
//get the actual bitmap data
stream.seekg(dataOffset);
stream.read(imgBuffer,dataSize);
stream.close();
return true;
}
-BIG- 编辑:为了找出问题所在,我将 ifstream 从函数移至类的私有(private)成员。该函数现在的作用完全相同,只是它使用 stream.open() 打开文件。
现在可以正常使用了。所以问题出在某种程度上......在函数内部每次都初始化ifstream,而不是仅仅在函数内部使用。仍然......没有意义,这不应该发生。
我真的很想知道这里的问题是什么?
老实说,有人知道这可能是什么原因吗?
最佳答案
需要调查的几点:
firstImageRead
是否初始化为true
?- 其余代码不知道
imgBuffer
有多大,因此进一步的处理可能是读取超出缓冲区末尾的部分。您的其余代码如何确定要从imgBuffer
中读取多少数据? - 如果任何图像的
dataSize
大于第一个图像,imgBuffer
将太小。 - 如果你在
DATASIZEINBYTES
位置读取的字符恰好是负数,你将尝试malloc()
大约 2GB。
旁注:您只读取图像大小的一个字节是否正确?图片有那么小吗?
关于c++ - 及时调试和文件流的真正奇怪的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/967311/