gpt4 book ai didi

c - 从非 void 函数中释放内存

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

我在释放内存时遇到问题:

我得到的输出是这样的:

==11073== 1,000 bytes in 1 blocks are definitely lost in loss record 5 of 5
==11073== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==11073== by 0x400B38: userInput (program.c:80)
==11073== by 0x400DFD: playGame (program.c:150)
==11073== by 0x4012E9: main (program.c:298)

我使用的变量是 input 和 answer,它们是在 main 之外定义的:

char *answer;
char *input;

我在 main 中使用的变量“answer”是这样的:

line 150    answer = userInput();

函数是这样的:

char* userInput()
{
printf ("> ");

input = malloc (sizeof(char) * 1000); // THIS is LINE 80
fgets(input, 1000, stdin);
//input = realloc(input, strlen(input));

strtok(input, "\n");

int i = 0;
while (i < strlen(input))
{
input[i] = tolower(input[i]);
i++;
}

if (strcmp(input, "y") == 0 || strcmp(input, "yep") == 0 || strcmp(input, "yeah") == 0
|| strcmp(input, "absolutely") == 0 || strcmp(input, "correct") == 0)
input = "yes";

if (strcmp(input, "n") == 0 || strcmp(input, "nope") == 0)
input = "no";

return input;
}

最佳答案

你在这里泄漏了内存:

input = "yes";

这里:

input = "no";

input 现在指向一个字符串文字,它之前指向的内存丢失了。

关于c - 从非 void 函数中释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27378535/

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