1

在下面代码的末尾,我需要将哪个指针插入 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调整它的大小,或者我可以跳过马尔洛克)?

4

1 回答 1

1

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

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

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

于 2014-06-23T19:30:06.490 回答