在char *的静态数组上使用free()

时间:2013-10-07 23:07:46

标签: c static malloc free

我有以下代码:

void fn(char *string , int flag)
{
    static char* array_of_strings[100];
    static int index = 0;

    if(flag)
    {
        array_of_strings[index] = (char *)malloc(10);
        strcpy(array_of_strings[index] , string);
        index++;
    }
    else
    {
        //How should I deallocate the memory here?
        index--;
    }
}

如果满足else块,array_of_strings [index]会发生什么?是自动处理还是会在fn()返回后保留?我应该使用这一行来代替评论:

array_of_strings[index] = 0;

或者我可以像这样使用free():

free(array_of_strings[index]);

这会释放malloc分配的内存块吗?

2 个答案:

答案 0 :(得分:3)

这没关系:

/* Allocate an array to hold 100 char * pointers: OK */
static char* array_of_strings[100];

/* Allocate space to hold one 9-character string: OK */
array_of_strings[index] = malloc(10);

/* Free string: OK */
free(array_of_strings[index]);

这会让你感到悲伤:

/* Whoops: step on the pointer, then try to free it.  Not good :( */
array_of_strings[index] = 0;
free(array_of_strings[index]);
  

问:如果else阻塞,array_of_strings [index]会发生什么   满足了?是自动处理还是会在fn()之后保留   返回?

答:如果你使用malloc,它将保持分配状态,直到你“释放()”它......或者直到程序终止。

答案 1 :(得分:3)

致电

free(array_of_strings[index]);

不释放char*的静态数组,它释放为动态分配的10 char保留的内存块,以及存储在{{1}中的指针指针数组。这是避免内存泄漏的正确方法。

另一方面,这一行使得无法访问动态分配的内存块:

static

这种情况通常被称为“内存泄漏”。你应该避免它。

请注意,将array_of_strings[index] = 0; d指针设置为零以避免意外解除引用并不常见,如下所示:

free

如果你这样做,你可以告诉free(array_of_strings[index]); array_of_strings[index] = 0; // Prevent a "dangling reference" 的指针在以后的某个时间不再有效。

相关问题