【问题标题】:Undefined behavior fopen, fclose [duplicate]未定义的行为 fopen,fclose [重复]
【发布时间】:2015-04-01 20:04:19
【问题描述】:

以下代码会导致未定义的行为吗?

FILE *fp;
fopen_s(&fp, "abc.bin", "rb");
fclose(fp);
fclose(fp); // accidentally closed an already closed file.

我知道在已经释放的数组上调用 free 会导致 UB。因此我问。

【问题讨论】:

  • 这当然是未定义的行为。
  • 在难以跟踪的复杂情况下,就像free(),如果在声明点将指针设置为NULL,然后在关闭或释放后,您可以在fclose()free() 调用之前检查它以节省很多悲伤。
  • @WeatherVane:但不幸的是,与free 不同的是,使用NULL 指针调用fclose 的定义并不明确。我建议在free 之前“检查”NULL 是一件坏事。在调用fclose 之前检查NULL 绝对是一件好事。
  • 另见 Fclose a file that is already fclose 看起来像重复
  • @MatsPetersson if (!nullptr == fp) fclose(fp); 怎么样?

标签: c++ c file fopen fclose


【解决方案1】:

引用man fclose:

如果流参数是非法指针,或者是已传递给先前调用 fclose() 的描述符,则 fclose() 的行为未定义。

是的,这是未定义的行为。

【讨论】:

  • 同意。一个实现可以总是new/mallocfopen(_s)() 中的FILEdelete/freefclose() 中,或者它可以使用私有缓存,并且两者都是合法的。在将FILE* 指针传递给fclose() 之后,调用者不应对其有效性做出任何假设,只需将其设为NULL 并移动它即可。
  • 为什么说流参数?此处不使用流
  • @ShafikYaghmour:ISO C11 草案 N1570,7.21.3 标准。 4:The value of a pointer to a FILE object is indeterminate after the associated file is closed (including the standard text streams).
猜你喜欢
  • 1970-01-01
  • 2014-12-02
  • 2015-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多