[英]simple string list in c is leaking memory(malloc and realloc)
问题是我无法释放它,控制台输出指针与释放函数内部相同,在调用realloc时从函数StringList_add的行处检测到xcode。
typedef struct stringlist_s {
int max_str;
char **str;
}stringlist_t;
//functions
stringlist_t *StringList_new()
{
stringlist_t *lst = (stringlist_t *)malloc(sizeof(stringlist_t));
return lst;
}
void StringList_add(stringlist_t *str_list,char *str)
{
if(!str)
return;
if(!str_list)
return;
str_list->str = (char **)realloc(str_list->str, sizeof(char *) * (str_list->max_str+1));
str_list->str[str_list->max_str] = (char *)malloc(strlen(str) + 1);
memcpy(str_list->str[str_list->max_str], str, strlen(str) + 1);
str_list->max_str++;
}
void StringList_release(stringlist_t *strList)
{
if(!strList) {
printf("Releasing empty pointer\n");
return;
}
for(int i = 0 ; i < strList->max_str; ++i )
{
free(strList->str[i]);
printf("pointer inside is %p\n",strList->str[i]);
}
printf("list before is %p\n",strList);
free(strList);
printf("list now is %p\n",strList); //value is the same as previous printf
}
我只是用它来测试上面的代码:
stringList_t *a = StringList_new();
StringList_add(a,"abc");
StringList_add(a,"edf");
StringList_release(a);
一个问题是StringList_new()
分配了一个新的stringList_t
但从未初始化其成员。 在调用realloc()
:
str_list->str = (char **)realloc(str_list->str, sizeof(char *) *
(str_list->max_str+1));
str_list->str
或str_list->max_str
初始化。 从参考页面获取realloc()
:
它必须事先由malloc(),calloc()或realloc()分配,并且尚未用free()释放,否则,结果是不确定的。
与统一指针一起使用时会发生这种情况。
改成:
stringlist_t *StringList_new()
{
stringlist_t *lst = malloc(sizeof(*lst));
lst->max_str = 0;
lst->str = NULL;
return lst;
}
不要转换malloc()
或realloc()
的返回值。 将NULL
指针传递给realloc()
很好,在这种情况下,其行为类似于malloc()
。 使用realloc()
将返回值存储在临时指针变量中,以避免在realloc()
失败的情况下发生内存泄漏:
char** tmp = realloc(str_list->str, sizeof(*tmp) * (str_list->max_str+1));
if (tmp)
{
str_list->str = tmp;
}
注意我没有在StringList_new()
使用calloc()
,因为根据C标准,所有零位都不需要表示空指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.