How to free an array of char-pointer?

谁说胖子不能爱 提交于 2019-12-23 19:19:47

问题


I use this Method to convert values from a list into an array for use in an execvp()-Systemcall:

char **list2argarray(struct shellvalue *values, int count)
{
    char **array = (char **)malloc((count + 1) * sizeof(char *));
    int i = 0;

    while (values)
    {
        char *word = values->word;

        array[i] = (char *)malloc(sizeof(word) + 1);
        strcpy(array[i], word);
        values = values->next;
        i++;
    }
    array[i] = NULL;
    return array;
}

What is a proper way to free such Arrays? I tried it with things like

void freeargpointer(char **array, int count)
{
    int i = 0;

    while (*array)
    {
        free(*array);
        (*array)++;
    }
}

But everytime when i reach the free-syscall, while debugging, the programm crashes with errors like this one:

free(): invalid next size (fast): 0x000000000060c180 ****


回答1:


The problem is that (*array)++ doesn't give you the next pointer you allocated, so you can't free it. Your free routine should be:

void freeargpointer(char** array, int count)
{
    int i;

    for ( i = 0; array[i]; i++ )
        free( array[i] );

    free( array );
}

Or, similarly,

void freeargpointer(char** array, int count)
{
    char **a;

    for ( a = array; *a; a++ )
        free( *a );

    free( array );
}



回答2:


This line is wrong.

(*array)++;

You need to have.

++array;



回答3:


I tried this code and it works, maybe it helps you.

 void freeargpointer(char **array, int count)
{
    for(int i=0;i<count;++i)
    free(++array[i]);
}

Edit: I'm sorry to forget count it. Normally code is above.



来源:https://stackoverflow.com/questions/23436669/how-to-free-an-array-of-char-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!