gpt4 book ai didi

c - C 中标准输入的内存泄漏

转载 作者:行者123 更新时间:2023-11-30 21:06:09 26 4
gpt4 key购买 nike

我的代码遇到了内存泄漏问题。我相信它来自 stdin 。我尝试关闭(0),但没有成功。下面是我的代码

 char line[MAX_BUFFER] = {};
char *commands;
while(!feof(stdin)) {
fputs("? ",stdout);

if(fgets(line, MAX_BUFFER , stdin))
{
Command cmd = {};
commands = parse(&cmd, line);
printf("%s",commands);
free(commands);

}

}

return 0;

我的parse.c基本上就是这样做的

    char result[250] = "some text string here";
char *target = malloc(sizeof(char) * 250);
target = strdup(result);
return target

我的 valgrind 输出看起来像这样

==26303== FILE DESCRIPTORS: 3 open at exit.
==26303== Open file descriptor 2: /dev/pts/4
==26303== <inherited from parent>
==26303==
==26303== Open file descriptor 1: /dev/pts/4
==26303== <inherited from parent>
==26303==
==26303== Open file descriptor 0: /dev/pts/4
==26303== <inherited from parent>
==26303==
==26303==
==26303== HEAP SUMMARY:
==26303== in use at exit: 500 bytes in 2 blocks
==26303== total heap usage: 4 allocs, 2 frees, 545 bytes allocated
==26303==
==26303== 500 bytes in 2 blocks are definitely lost in loss record 1 of 1

最佳答案

strdup() 和 malloc() 都在分配内存!您可以删除 parse.c 中的第二行并编辑第三行以表示

char * target = strdup(result);

它会工作得很好。

另外,在使用完内存后,不要忘记使用 free(pointerToMemoryAllocation) 释放内存

关于c - C 中标准输入的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50531481/

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