为了解释我的问题,这是极简主义的main.cc:
#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;
}
Run Code Online (Sandbox Code Playgroud)
和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;
}
Run Code Online (Sandbox Code Playgroud)
函数read_stdin()可以从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)
Run Code Online (Sandbox Code Playgroud)
我编译为 g++ -O0 -g main.cc -o test
我知道这12个字节是"输出",但为什么有些字节丢失了?我使用delete [],即使STDIN或输入中没有任何内容,输出也会为NULL吗?
我误解了为什么还有这12个字节,我哪里错了?
先感谢您 :)
编辑
感谢Vaughn Cato,DietmarKühl和Richard J. Ross III,我改变了方言:
output = fgets(tmp_buffer, len, input);
if ( output != NULL ) {
Run Code Online (Sandbox Code Playgroud)
至
if ( fgets(output, len, input) != NULL ) {
Run Code Online (Sandbox Code Playgroud)
您已output使用不同的指针替换,因此您不会删除您分配的相同内容:
output = fgets(tmp_buffer, len, input);
Run Code Online (Sandbox Code Playgroud)
我不确定为什么read_stdin有这个output参数.如果您只需要检查fgets的结果,那么您可以使用局部变量:
inline bool read_stdin(char *tmp_buffer, const size_t &len, FILE *input) {
char *output = fgets(tmp_buffer, len, input);
.
.
.
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
124 次 |
| 最近记录: |