gpt4 book ai didi

c - 程序内存泄漏? C

转载 作者:行者123 更新时间:2023-11-30 16:49:49 25 4
gpt4 key购买 nike

动态分配一个cstrings数组来分隔传递给它的字符串。 Valgrind 说我有 7 个分配,但只有 3 个释放。但我不确定如何在使用返回数组的函数时释放内存。

这是函数

char ** func( char * str, char del ) {
char** substrings;
char* word;
int len = 0, capacity = 2, i, x;
substrings = malloc(sizeof(char*) * (capacity + 1));
for (i = 0; i <= capacity; i++){
substrings[i] = NULL;
}
while (*word != '\0') {
if (len >= capacity){
/* double size */
char **temp;
capacity *= 2;
temp = malloc(sizeof(char*) * (capacity + 1));
for (i = 0; i < len; i++) {
temp[i] = substrings[i];
}
for (i = len; i <= capacity; i++) {
temp[i] = NULL;
}
substrings = temp;

temp = NULL;
free(temp);

}
}
return substrings;
}

最佳答案

根据您的代码,

if (len  >= capacity){
/* double size */
char **temp;
capacity *= 2;
temp = malloc(sizeof(char*) * (capacity + 1));
for (i = 0; i < len; i++) {
temp[i] = substrings[i];
}
for (i = len; i <= capacity; i++) {
temp[i] = NULL;
}
free(substrings); // release old memory
substrings = temp; // this line causes substrings pointer leak if you assign new address to it without free

temp = NULL;
free(temp); // no need free NULL

}

实际上,如果您将 valgrind--track-origins=yes 选项一起使用,它会报告哪条线路发生泄漏。

关于c - 程序内存泄漏? C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42453032/

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