解释我的问题,这是极简main.cc:使用delete []但字节肯定丢失了,为什么?
#include "./main.h"
int main(int argc, char *argv[]) {
char *buffer = new char[12];
char *output = new char[12];
FILE *input = fopen("file.test", "r");
while (read_stdin(buffer, 12, input, output)) {
// Operations on output
// (...)
}
fclose(input);
delete[] output; output = 0;
delete[] buffer; buffer = 0;
return 0;
}
而且main.h:
#include <cstdio>
#include <cstring>
inline bool read_stdin(char *tmp_buffer, const size_t &len, FILE *input, char *&output) {
output = fgets(tmp_buffer, len, input);
if (output != NULL) {
char *lf = strchr(output, '\n');
if (lf != NULL) {
*lf = '\0';
}
return true;
}
return false;
}
功能read_stdin()可以从标准输入读,它解释了它的名字。
好,预期所有的工作,但是的valgrind告诉我的东西,如:
==6915== 12 bytes in 1 blocks are definitely lost in loss record 1 of 1
==6915== at 0x4C29527: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==6915== by 0x4008A2: main (main.cc:6)
我编译为g++ -O0 -g main.cc -o test
据我了解,这12个字节为“输出”,但为什么会出现一些字节丢失?我使用delete [],即使STDIN或输入中没有任何内容,输出也会是NULL吗?
我误解为什么仍然有这12个字节,我错在哪里?
预先感谢您:)
编辑
由于沃恩卡托,迪特马尔·库尔和理查德·罗斯III,我改线:
output = fgets(tmp_buffer, len, input);
if (output != NULL) {
到
if (fgets(output, len, input) != NULL) {
可能是一个valgrind错误,但你的代码看起来是正确的。 –