the problem is I can’t free it,the console output pointer are the same inside free function, the xcode detected at the line from function StringList_add when realloc called.
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
}
I just use this to test the code above:
stringList_t *a = StringList_new();
StringList_add(a,"abc");
StringList_add(a,"edf");
StringList_release(a);
A problem is that
StringList_new()allocates a newstringList_tbut never initialises it members. At the call torealloc():neither
str_list->strorstr_list->max_strhave been initialised. From the reference page forrealloc():which will be the case when used with an unitialised pointer.
Change to:
Don’t cast the return value of
malloc()orrealloc(). Passing aNULLpointer torealloc()is fine, it behaves likemalloc()in that case. When usingrealloc()store the return value in a temporary pointer variable to avoid a memory leak in the event thatrealloc()fails:Note I did not use
calloc()inStringList_new()as according the C standard all bits zero need not represent a null pointer.