2013-01-04 31 views
0

解释我的问题,这是极简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) { 
+0

可能是一个valgrind错误,但你的代码看起来是正确的。 –

回答

7

您已更换output用不同的指针,这样你就不会删除您分配了相同的事情:我不知道为什么read_stdinoutput参数

output = fgets(tmp_buffer, len, input); 

。如果你只需要检查fgets的结果,那么你可以使用本地变量:

inline bool read_stdin(char *tmp_buffer, const size_t &len, FILE *input) { 
    char *output = fgets(tmp_buffer, len, input); 
    . 
    . 
    . 
} 
+0

不,'fgets'返回成功时传入的指针。 –

+1

@ RichardJ.RossIII它没有通过相同的指针,是吗? –

+0

我的错误是'read_stdin(...,char *&output)'的原型? –

相关问题