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

Allocation memory using realloc, exact size I need

我正在用 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;
}

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