费罗尔导致访问冲突

ferror leads to access violation

本文关键字:访问冲突 罗尔导      更新时间:2023-10-16

我在调用ferror(f)时收到访问冲突。问题是我检查f不是空指针。我还能够在收到访问冲突之前读出文件。它发生在 http://www.bzip.org 的 bzip 库中(仅经过修改,以便可以构建,例如禁用错误并删除多个主要功能(。

这是我的主要

int main() {
int e = 0;
int *error = &e;
FILE *f = fopen("./test", "r"); //open file
if (f == NULL) {  //Changed, as beforehand both checks happend at the same time
//However the programm passes both checks
std::cout << "f* is NULLn";
exit(1);
}
if (ferror(f)) {
std::cerr << "Can't open the file " << ferror(f) << 'n';
exit(1);
}
char *c = char[20];
fread(c, 1, 20, f); // Here we can read succesfully out of the file
std::cout << c;
BZFILE* bzfile = BZ2_bzReadOpen(error, f, 1, 0, NULL, 0); //The failing function call
}

这是库外失败的函数:

BZFILE* BZ_API(BZ2_bzReadOpen) 
( int*  bzerror, 
FILE* f, 
int   verbosity,
int   small,
void* unused,
int   nUnused )
{
bzFile* bzf = NULL;
int     ret;
BZ_SETERR(BZ_OK);
if (f == NULL || //A check in the function itself, which also passes
(small != 0 && small != 1) ||
(verbosity < 0 || verbosity > 4) ||
(unused == NULL && nUnused != 0) ||
(unused != NULL && (nUnused < 0 || nUnused > BZ_MAX_UNUSED)))
{ BZ_SETERR(BZ_PARAM_ERROR); return NULL; };
if (ferror(f)) // Here is the access violation
{ BZ_SETERR(BZ_IO_ERROR); return NULL; };
}

具体错误是

Exception thrown at 0x0003E5C4 in wikiParser.exe: 0xC0000005: Access violation executing location 0x0003E5C4.

我尝试将程序移动到另一台PC,但是仍然发生相同的错误。指针不为 NULL;有两个检查,我可以自己打电话给ferror,而不会违反访问。

if(f == NULL || ferror(f)) // Check that f isn't NULL nor has an Error
std::cerr << "Can't open the file " << ferror(f)  << 'n';

换句话说,如果f== NULL那么cerr << ferror(f).

难怪它会爆炸。