如何释放一个字符指针数组? [英] How to free an array of char-pointer?

查看:263
本文介绍了如何释放一个字符指针数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此方法将列表中的值转换为数组,以便在execvp()-Systemcall中使用:

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)++;
    }
}

但是每次当我到达free-syscall时,在调试时,程序都会崩溃,并显示如下错误:

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

free():下一个大小无效(快速):0x000000000060c180 ****

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

推荐答案

问题是(*array)++不会给您分配的下一个指针,因此您不能释放它.您的免费例程应为:

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 );
}

或者类似地,

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

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

    free( array );
}

注意:我删除了count参数,因为它是不必要的.

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

这篇关于如何释放一个字符指针数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆