【发布时间】:2020-11-08 02:48:17
【问题描述】:
我的问题是我相信我的代码是正确的,但是,我继续得到 realloc(): invalid next size。我已经查找了如何解决 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;
}
【问题讨论】:
-
这通常意味着您已经超出了缓冲区或在释放后使用了分配的区域。尝试使用 valgrind 等工具快速找到这些。
-
如果您要发布一个可以编译和运行的完整程序minimal reproducible example(主要功能,
#includes,等等),有人可能愿意为您测试它.请注意,malloc 错误通常与触发错误的函数位于完全不同的位置,因此完整的示例也很重要;该错误可能在您未向我们展示的代码中。 -
我不能说我已经对您的代码进行了详细分析,但是在很多情况下,您的代码如
result->order = bigorder;紧跟free(bigorder);。这些对我来说似乎是代码的味道:如果您要立即使该指针无效(通过释放它),那么将指针分配给某物有什么意义。 -
是的,更糟糕的是:如果您返回该指针,调用者很可能会使用它。
-
@Nate ...很可能会尝试使用它。 ;)
标签: c realloc round-robin