[英]C - Freeing memory allocated with malloc
我正在 C 中编程,并且有一个 function insert()
分配 memory 和malloc()
。 这个 function 是从另一个名为SJF()
的 function 调用的。 SJF()
function 多次调用insert()
。
我想知道我应该在哪里以及如何free()
这个 memory。 我不想每次都释放 memory ,所以在insert()
function 中这样做是行不通的。 那么最好的办法是从 function 返回分配的 memory 然后以这种方式释放它?
void insertJob (struct node **head, int key, int data) {
struct node * new_node = NULL;
struct node * last = NULL;
/*Create the new node*/
new_node = (struct node *)malloc(sizeof(struct node));
if (new_node == NULL)
{
printf("Failed to insert element. Out of memory");
return;
}
new_node->key = key;
new_node->data = data;
new_node->origBurst = data;
new_node->next = NULL;
/*No element in the linked list. So point head to the new node*/
if( *head == NULL)
{
*head = new_node;
return;
}
/*Traverse to the last node*/
last = *head;
while(last->next) last = last->next;
/*Point last node's link (next pointer) to the new node*/
last->next = new_node;
return;
}
void sjf(int count, const int *submit, const int *burst) {
int response = 0, wait = 0, turnaround = 0;
struct node nd;
nd.minJob = 0;
// Create job index and clock
int job = 0, clock = 0, i = 0;
// Loop through all the jobs (SJF)
while(job<count) {
// Update clock as necessary
if(clock < submit[job]) {
clock = submit[job];
}
// Bubble up the shortest job in the ready queue
// Prepare the ready Queue
for(int j = i; j < count; j++) {
if(submit[j] <= clock) {
insertJob(&head, submit[j],burst[j]);
i++;
}
}
// Find shortest job from ready queue
shortestJob(head, &nd);
// Calculate the next event (job end)
int nextevent = clock + nd.minData;
// Calculate statistics
int myresp = clock - nd.minJob;
int myta = nextevent - nd.minJob;
int mywait = myta - nd.minData;
response += myresp;
turnaround += myta;
wait += mywait;
// Set clock to the next event time
clock = nextevent;
// Increment job
job++;
// Loop back to top
removeJob(nd.minJob, nd.minData);
}
printf("Shortest Job First Scheduler\n");
printf("Resp: %.2f, Wait: %.2f, T/A: %.2f\n", (float) response / count,
(float) wait / count,
(float) turnaround / count);
//possibly free() memory here
}
这段代码只是一个片段。
我想在你调用 printf 之前,你可以在完成使用后清除整个链接列表。 您必须释放列表中的整个节点而不仅仅是头,这意味着您必须对其进行迭代,将下一个节点的地址保存在临时变量中并释放当前节点,然后再将存储在 tmp 中的下一个节点分配回当前指针:
// [...] previous code
struct node *tmp;
struct node *ptr = *head;
while (ptr) {
tmp = ptr->next
(void)ptr;
free(ptr);
ptr = tmp;
}
printf("Shortest Job First Scheduler\n");
printf("Resp: %.2f, Wait: %.2f, T/A: %.2f\n", (float) response / count,
(float) wait / count,
(float) turnaround / count);
注意:您可以调用 function,您称之为“free_whole_list()”,它可能会更好,因为您可以将其用于其他项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.