问题是我无法释放它,控制台输出指针在 free 函数内部是相同的,当 realloc 调用时,xcode 在函数 StringList_add 的行中检测到。
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);