【问题标题】:pointer to a pointer, which is pointing to a memory block, which pointer should be freed?指向一个指针的指针,它指向一个内存块,应该释放哪个指针?
【发布时间】:2014-08-13 22:57:35
【问题描述】:

在下面代码的末尾,我需要将哪个指针插入 free()、array 或 temp_array?哪一个或哪一个会释放内存块有关系吗?

int *array = 0;
int *temp_array = 0;
int count = 0;

array = malloc(sizeof(int));

// skipping code where count is calculated...

temp_array = realloc(array, count * sizeof(int));

if (temp_array == NULL) {
    free(array);
    // some error message
    return;
}
array = temp_array;

// skipping section of code, which reads numbers from a file and loads them into an array
// amount of numbers read can be 0 to whatever

free (array); // free array or temp_array?

此外,如果尝试为其分配内存的指针为 NULL,是否可以使用 realloc 分配内存块(换句话说,我是否需要先使用 malloc 分配内存,然后使用 realloc 调整大小,或者可以我跳过 malloc)?

【问题讨论】:

    标签: c malloc free realloc pointer-to-pointer


    【解决方案1】:

    没关系 - temp_arrayarray 都指向同一个内存块。我更喜欢temp_array,因为这样 realloc 和 free 指针匹配。根据您的工作代码,为了保护,您可以考虑将两个指针都分配给 NULL 以防止两次释放内存。 free(NULL) 是安全的 - 不执行任何操作。

    关于一个整数的初始分配 - 有必要吗?从显示的代码来看,最好在堆栈上定义一个 int。

    编辑: 在来自 OP(在 cmets 中)的更多信息之后,似乎可以使用包含文件中记录数的标头值来简化代码。这消除了重新分配的需要,并允许在读取文件值之前分配内存。

    【讨论】:

    • 我不确定我是否以最好的方式编写它,但代码来自一个函数,该函数从文件中读取整数并将它们加载到数组中。整数的数量可以是 0 到任何值。我在循环文件中的数字的 for 循环之外做了 malloc,在 for 循环内我使用 realloc 来增加数组的大小。我不确定是否可以在 NULL 指针上分配内存,所以这就是我首先调用 malloc 的原因。如果指针为 NULL,是否可以使用 realloc 分配内存?即 ptr = realloc (NULL, count * sizeof(int));
    • 好的。我会在包含记录数的文件中创建一个标题。然后该函数将首先读取头 int,分配足够的内存然后读取所有值。
    • 好主意!没想到。
    • 好 - 我会在一分钟内更新答案。顺便说一句,如果有帮助,请投票或接受答案。谢谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多