0

我有以下代码:

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 分配的内存块吗?

4

2 回答 2

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 某些东西,它会一直保持分配状态,直到你“free()”它……或者直到程序终止。

于 2013-10-07T23:10:57.350 回答
3

一个电话

free(array_of_strings[index]);

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

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

array_of_strings[index] = 0;

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

free请注意,将d 指针设置为零以避免意外取消引用它并不少见,如下所示:

free(array_of_strings[index]);
array_of_strings[index] = 0; // Prevent a "dangling reference"

如果你这样做,你可以告诉指针在array_of_strings[index]以后不再有效。

于 2013-10-07T23:12:02.643 回答