How to free an array of char-pointer?

13,731

Solution 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 i;

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

    free( array );
}

Or, similarly,

void freeargpointer(char** array)
{
    char **a;

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

    free( array );
}

NOTE: I removed the count argument since it is unnecessary.

Solution 2

This line is wrong.

(*array)++;

You need to have.

++array;
Share:
13,731
masked_m0nkey
Author by

masked_m0nkey

Updated on June 27, 2022

Comments

  • masked_m0nkey
    masked_m0nkey about 2 years

    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 ****

  • Wai Ha Lee
    Wai Ha Lee about 9 years
    Where is count used?
  • MattSom
    MattSom over 4 years
    So where is count used?
  • lurker
    lurker over 4 years
    @MattSom it's not. I carried it along unwittingly from the OP's original code. I'll remove it for clarity.
  • chux - Reinstate Monica
    chux - Reinstate Monica over 4 years
    Could add about incorrect array[i] = (char *)malloc(sizeof(word) + 1);. Likely needs array[i] = (char *)malloc(strlen(word) + 1);