如何解决尝试制作循环赛的C语言新手 Realloc:下一个尺寸无效的
我的问题是我认为我的代码是正确的,但是,我继续得到一个realloc():下一个大小无效。我已经查找了如何解决重新分配问题,但仍然遇到了问题。我试图确保释放这些值。由于我不知道订单队列的数量,因此我使用了malloc。它遍历给定的突发值队列,并将其与量子进行比较。该代码应返回队列的顺序,周转时间队列和总处理时间。我在哪里感到困惑/错误?
rr_result *rr(int *queue,int np,int tq)
{
rr_result *result = malloc(sizeof(rr_result));
result->np= np;
result->turnarounds = malloc(sizeof(int) * np);
// code here to assign values to result->turnarounds,result->order,and result->order_np
int temp[np],curr,check[np],startp[np],flag,newlen,*neworder=NULL,*bigorder=NULL,*turna=NULL;
neworder= (int *) malloc(sizeof(int) * np);
turna = (int *) malloc(sizeof(int) * np);
for(int i = 0; i < np; i++){ // Makes an array of the burst times we can use to update
temp[i]= queue[i];
check[i] = 0;
}
curr = 0; //The current time value of the array
newlen = 0; //Length for the results array
while (1)
{
flag = 0; //To exit out of the infinite rr loop
for (int i = 0; i < np; i++)
{
if (temp[i]>0) //Check if there is still burst time left
{
flag = 1; //Something still must be processed
if (check[i] == 0)
{
startp[i] = curr; //Save the process start time
check[i] = 1; // Save the flag that this specific process has started
}
if (temp[i] > tq)
{
curr += tq; //Update current time value
temp[i] -= tq; //Decrease the burst time by the quantum value
}else
{
curr += temp[i]; //Update current time value
turna[i] = curr - startp[i]; //Calculate the turnaround value by subtracting the start time from current time
temp[i]= 0; //Update to show the process is finished
}
}
if(newlen > np){
bigorder = (int *) realloc(neworder,(newlen*newlen)* sizeof(int));
free(neworder);
bigorder[newlen] = i;
newlen++;
}else{
neworder[newlen] = i;
newlen++;
}
}
if (flag == 0)
{
if(bigorder != NULL){
result->order = bigorder;
free(bigorder);
}else
{
result->order = neworder;
free(neworder);
free(bigorder);
}
result->turnarounds = turna;
result->order_n = curr;
free(turna);
break;
}
}
return result;
}
解决方法
bigorder = (int *) realloc(neworder,(newlen*newlen)* sizeof(int));
free(neworder);
这是错误的。传递指向realloc
的指针后,请勿释放它(除非realloc
失败,您应该对其进行测试)。完成操作后,您可以释放bigorder
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。