Valgrind 在 fclose() 中说 "Invalid write"

Valgrind says about "Invalid write" in fclose()

我使用 fmemopen() 创建了一个流。我用 fclose() 关闭它并在读取后释放缓冲区。 Valgrind 报告有关 fclose() 行的问题:

==9323== Invalid write of size 8
==9323==    at 0x52CAE52: _IO_mem_finish (memstream.c:139)
==9323==    by 0x52C6A3E: fclose@@GLIBC_2.2.5 (iofclose.c:63)
==9323==    by 0x400CB6: main (main.cpp:80)
==9323==  Address 0xffefffa80 is just below the stack ptr.  To suppress, 
use: --workaround-gcc296-bugs=yes

发生了什么事?也许 fclose() 无法正确关闭内存流?或者,也许 valgrind 无缘无故地担心,我可以忽略它?

由于您尚未发布代码,以下纯属猜测。您向流中写入的输出可能比打开它时承诺的要多。您是否考虑了最终的 NUL(如果您没有使用 "b" 打开)?

您是否阅读了手册页中的以下内容?

When a stream that has been opened for writing is flushed (fflush(3)) or closed (fclose(3)), a null byte is written at the end of the buffer if there is space. The caller should ensure that an extra byte is available in the buffer (and that size counts that byte) to allow for this.

Attempts to write more than size bytes to the buffer result in an error. (By default, such errors will be visible only when the stdio buffer is flushed. Disabling buffering with setbuf(fp, NULL) may be useful to detect errors at the time of an output operation. Alternatively, the caller can explicitly set buf as the stdio stream buffer, at the same time informing stdio of the buffer's size, using setbuffer(fp, buf, size).)

遵循后面的建议应该会揭示超出容量的写入。

是我的错。我写道,我使用 fmemopen() 打开一个流,但这段代码不是 运行,我得到了之前用 open_memstream() 生成的流。虽然这个流是为写入而打开的,但我可以从中读取。但是 valgrind 报告了问题。我修复了我的代码,valgrind 没有发现错误。