【问题标题】:Allocation memory using realloc, exact size I need使用 realloc 分配内存,我需要的确切大小
【发布时间】:2015-03-29 20:34:09
【问题描述】:

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

【问题讨论】:

  • 不要像那样一一分配数组;它最终变得昂贵。单独记录已分配记录的数量和正在使用的数量。当您分配更多内存时,每次分配两倍。这避免了线性分配没有的二次行为。
  • 或者,当您知道还有其他学生的数据要存储时,读入局部变量 Student data; 并在数组中分配更多数据。
  • 感谢乔纳森的回复。你能用你提到的替代方式告诉我你的意思吗?

标签: c memory dynamic struct allocation


【解决方案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;
}

请注意,在调用 Error_Msg() 之前,您可以(也许应该)free(temp)。请注意,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) 成语,但你也可以解决这个问题。

【讨论】:

    猜你喜欢
    • 2016-07-04
    • 2014-04-04
    • 2019-07-20
    • 2021-12-23
    • 2015-01-27
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    • 1970-01-01
    相关资源
    最近更新 更多