gpt4 book ai didi

c - 使用 realloc 分配内存,我需要的确切大小

转载 作者:行者123 更新时间:2023-11-30 17:17:55 29 4
gpt4 key购买 nike

我正在用 C 编写代码,但在准确分配我需要的大小时遇到​​问题。我使用 while 循环和 realloc 函数,并且当循环完成时,我有一个备用内存(比我需要的+1)。我找不到一种方法来分配我需要的确切大小。

最佳答案

一次增加一条记录的数组大小 - 对性能不利,但相对简单:

int InputData(Student **p_array, FILE*fp)
{
Student *temp = 0;
Student data;
int i = 0;

while (fscanf(fp, "%s%d%d%d", data.name, &data.grades[0],
&data.grades[1], &data.grades[2]) == 4)
{
size_t space = ++i * sizeof(Student);
Student *more = (Student *)realloc(temp, ++i * sizeof(Student));
if (more == NULL)
Error_Msg("Memory allocation failed!");
temp = more;
temp[i-1] = data;
}

*p_array = temp;
return i;
}

请注意,您可以(也许应该)free(temp)在调用Error_Msg()之前。请注意 realloc()不使用ptr = realloc(ptr, new_size)这是习惯用法,因为如果重新分配失败,就会丢失(泄漏)之前分配的内存。

另一种选择 - 在返回之前缩小分配:

int InputData(Student **p_array, FILE*fp)
{
int i = 1;
Student *temp = (Student *)malloc(sizeof(Student));

if (temp == NULL)
Error_Msg("Memory allocation failed!");
while (fscanf(fp, "%s%d%d%d", temp[i - 1].name, &temp[i - 1].grades[0],
&temp[i - 1].grades[1], &temp[i - 1].grades[2]) == 4)
{
i++;
temp = (Student*)realloc(temp, sizeof(Student)*i);
if (temp == NULL)
Error_Msg("Memory allocation failed!");
}
assert(i > 0);
temp = (Student *)realloc(temp, sizeof(Student) * (i - 1));
*p_array = temp;
return i;
}

我不喜欢这个,因为 temp = realloc(temp, new_size)习语,但你也可以解决这个问题。

关于c - 使用 realloc 分配内存,我需要的确切大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29334519/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com