gpt4 book ai didi

c - 分配超过需要的

转载 作者:太空宇宙 更新时间:2023-11-04 03:25:13 26 4
gpt4 key购买 nike

我写了一段代码,分配了一个缓冲区,该缓冲区被分配了文件的内容。通过 valgrind 运行代码给了我这个

总堆使用量:9 次分配,7 次释放,分配 10,905 字节

如果我没记错的话代码只分配了 3 次,我在需要的时候处理定位。

void read_from_file (const char* filename, size_t length, char* buffer)
{
/* put your code here */
FILE* fOpen;

buffer = (char*)malloc(length+1);
fOpen = fopen(filename, "r");

if(!buffer) // --- Failed to allocate
printf("Failed to allocate...\n");

else if(!fOpen){ // --- Failed to open file
free(buffer);
fprintf(stdout, "Failed to read %s\n", filename);
buffer = NULL;
}

else if(fgets(buffer, length+1, fOpen)!=NULL){ // Buffer has been copied
fprintf(stdout, "buff is: %s\n", buffer);
free(buffer);
buffer = NULL;
}
else{ // --- Failed to copy correctly
fprintf(stdout, "Failed to copy %s file...\n", filename);
free(buffer);
buffer = NULL;
}
}

void main (int argc, char **argv)
{
char* buff = NULL;

read_from_file("test1.txt",10,buff);
read_from_file("test2.txt",10,buff);
read_from_file("test3.txt",10,buff);

}

最佳答案

看起来你没有内存泄漏,但你没有关闭你打开的文件。这是 Valgrind 报告中“仍可访问” block 的来源。从 read_from_file() 函数返回之前只需 fclose(fOpen)

此外,main() 的返回类型是int,而不是void。这是您更新后的代码:

#include <stdio.h>
#include <stdlib.h>

void read_from_file (const char* filename, size_t length, char* buffer)
{
/* put your code here */
FILE* fOpen;

buffer = malloc(length+1);
fOpen = fopen(filename, "r");

if(!buffer) // --- Failed to allocate
printf("Failed to allocate...\n");

else if(!fOpen){ // --- Failed to open file
free(buffer);
fprintf(stdout, "Failed to read %s\n", filename);
buffer = NULL;
}

else if(fgets(buffer, length+1, fOpen)!=NULL){ // Buffer has been copied
fprintf(stdout, "buff is: %s\n", buffer);
free(buffer);
buffer = NULL;
}
else{ // --- Failed to copy correctly
fprintf(stdout, "Failed to copy %s file...\n", filename);
free(buffer);
buffer = NULL;
}

if (fclose(fOpen) != 0) {
fprintf(stderr, "Unable to close file");
}
}

int main (void)
{
char* buff = NULL;

read_from_file("test1.txt",10,buff);
read_from_file("test2.txt",10,buff);
read_from_file("test3.txt",10,buff);

return 0;
}

Valgrind 的输出:

==3564== HEAP SUMMARY:
==3564== in use at exit: 0 bytes in 0 blocks
==3564== total heap usage: 6 allocs, 6 frees, 1,737 bytes allocated
==3564==
==3564== All heap blocks were freed -- no leaks are possible
==3564==
==3564== For counts of detected and suppressed errors, rerun with: -v
==3564== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

关于c - 分配超过需要的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41732330/

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