【问题标题】:Using free() on static array of char*在 char* 的静态数组上使用 free()
【发布时间】:2013-10-07 23:07:46
【问题描述】:

我有以下代码:

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

【问题讨论】:

  • 像往常一样,每个malloc(或realloc等)都应该有一个对应的free

标签: c static malloc free


【解决方案1】:

没关系:

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

【讨论】:

  • 问:这有帮助吗?有什么问题吗?
  • 感谢您的帮助!
【解决方案2】:

一个电话

free(array_of_strings[index]);

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

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

array_of_strings[index] = 0;

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-18
    • 2015-07-29
    • 2011-04-18
    • 2011-04-29
    • 1970-01-01
    • 2015-08-27
    • 2016-01-08
    • 1970-01-01
    相关资源
    最近更新 更多