使用realloc分配内存,我需要的确切大小
我正在用C语言编写一段代码,但在分配所需的大小时遇到了一个问题。使用realloc分配内存,我需要的确切大小,c,memory,dynamic,struct,allocation,C,Memory,Dynamic,Struct,Allocation,我正在用C语言编写一段代码,但在分配所需的大小时遇到了一个问题。 我使用while循环和realloc函数,循环完成后,我有一个比我需要的多+1的空闲内存。而且我找不到一种方法来分配所需的确切大小。一次增加一条记录的数组大小-对性能不好,但相对简单: int InputData(Student **p_array, FILE*fp) { Student *temp = 0; Student data; int i = 0; while (fscanf(fp, "
我使用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之前,您可能需要freetemp。请注意,realloc不使用ptr=reallocptr,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=realloctemp是一个新的大小习惯用法,但您也可以解决这个问题。不要像那样逐个分配数组;结果很贵。单独记录分配的记录数和正在使用的记录数。分配更多内存时,每次分配两倍的内存。这避免了线性分配所不能避免的二次行为。或者,读入局部变量学生数据;当你知道还有其他学生的数据要存储时,在数组中分配更多的数据。谢谢你的回复。你能用你提到的另一种方式告诉我你的意思吗?