恐怖导致访问违规

时间:2017-08-17 17:55:28

标签: c++

调用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 NULL\n";
    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,而不会违反访问权限。

1 个答案:

答案 0 :(得分:3)

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)

难怪它会爆炸。