gpt4 book ai didi

c++ - 内存通过 new[] 泄漏而无需调用 new

转载 作者:太空宇宙 更新时间:2023-11-04 15:21:56 27 4
gpt4 key购买 nike

我从以下函数中得到内存泄漏:

int ReadWrite(int socket, char *readfile) {
FILE *rf = NULL;
rf = fopen(readfile, "rb");
fseek(rf, 0, SEEK_END);
int len = ftell(rf);
rewind(rf);

char readbuf[len + 1];

int res = fread(readbuf, len, 1, rf);
readbuf[len + 1] = '\0';
fclose(rf);
while (1) {
int wres = write(socket, readbuf, res);
if (wres == 0) {
cerr << "socket closed prematurely" << endl;
close(socket);
return EXIT_FAILURE;
}
if (res == -1) {
if (errno == EINTR)
continue;
cerr << "socket write failure: " << strerror(errno) << endl;
close(socket);
return EXIT_FAILURE;
}
break;
}
return EXIT_SUCCESS;
}

Valgrind 告诉我我通过这个操作泄露了 readfile(实际文件,而不是 readfile 的名称)中的字节数:

Address 0x4c3b67e is 0 bytes after a block of size 14 alloc'd
at 0x4A07C84: operator new[](unsigned long) (vg_replace_malloc.c:363)

让我感到困惑的是我从来没有在我的代码中使用 new[]。我检查了 fopen、ftell 和 fread,看它们是否在调用 new[] 的地方隐藏了“陷阱”,但在 cplusplus.com 上的文档中没有找到任何内容。我已经尝试了 new char[]/delete[]、malloc/free 和堆栈分配变量(上图)的所有不同组合,但我每次都收到相同的 valgrind 消息。有任何想法吗?谢谢。

最佳答案

你打电话

  • char readbuf[len + 1];

    后来

  • readbuf[len + 1] = '\0';

那不会溢出数组吗?

关于c++ - 内存通过 new[] 泄漏而无需调用 new,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16824708/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com