Valgrind表示存在内存泄漏,但我不知道这是什么。我尝试将free's放在append函数中,在main的末尾释放字符串,但它仍然会抱怨。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void append(char* string, char c)
{
int stringlength = strlen(string);
char* tmp = realloc(string, sizeof(char) * (stringlength + sizeof(char) + sizeof(char)));
if(tmp == NULL)
{
free(tmp);
free(string);
printf("Error appending character\n");
exit(1);
}
string = tmp;
string[stringlength] = c;
string[stringlength+1] = '\0';
}
int main()
{
char* string = malloc(sizeof(char));
string[0] = '\0';
printf("string before appending: %s\n", string);
append(string, 'c');
printf("string after appending: %s\n", string);
free(string);
return 0;
}
这是Valgrind的输出:https://pastebin.com/dtXFm5YC
(它在Pastebin中,因此Stack Overflow实际上会让我发布此问题
最佳答案
您的主要问题不是内存泄漏而是无效访问:
Invalid read of size 1
...
Address 0x49d0028 is 0 bytes inside a block of size 1 free'd
和无效的免费:
Invalid free() / delete / delete[] / realloc()
...
Address 0x49d0028 is 0 bytes inside a block of size 1 free'd
因为他们有不确定的行为
当您执行
char* tmp = realloc(string, sizeof(char) * (stringlength + sizeof(char) + sizeof(char)));
时,该释放的字符串来自main,因此在main中对它进行printf时,您将访问一个释放的块。请注意,事实是重新分配释放的块不是强制性的因为您不释放由realloc在分配中新分配的tmp,所以会造成内存泄漏
然后您再次释放已经由realloc释放的字符串
另外
sizeof(char) * (stringlength + sizeof(char) + sizeof(char))
很奇怪,您将sizeof(char)
更改为定义1,可以只是stringlength + 2
你想要那个 :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void append(char ** string, char c)
{
size_t stringlength = strlen(*string);
*string = realloc(*string, stringlength + 2);
if (*string == NULL)
{
fprintf(stderr, "cannot allocate memory\n");
exit(1);
}
(*string)[stringlength] = c;
(*string)[stringlength+1] = '\0';
}
int main()
{
char* string = malloc(1);
string[0] = '\0';
printf("string before appending: '%s'\n", string);
append(&string, 'c');
printf("string after appending: '%s'\n", string);
free(string);
return 0;
}
编译与执行:
pi@raspberrypi:/tmp $ gcc -g -pedantic -Wextra m.c
pi@raspberrypi:/tmp $ valgrind ./a.out
==17097== Memcheck, a memory error detector
==17097== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==17097== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==17097== Command: ./a.out
==17097==
string before appending: ''
string after appending: 'c'
==17097==
==17097== HEAP SUMMARY:
==17097== in use at exit: 0 bytes in 0 blocks
==17097== total heap usage: 3 allocs, 3 frees, 1,027 bytes allocated
==17097==
==17097== All heap blocks were freed -- no leaks are possible
==17097==
==17097== For counts of detected and suppressed errors, rerun with: -v
==17097== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)
关于c - 附加到字符串时C中的内存泄漏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55207997/