Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C programming: I\'m kinda sure there\'s nothing wrong with my function but it ke

ID: 3691733 • Letter: C

Question

C programming:

I'm kinda sure there's nothing wrong with my function but it kept showing:

This is main(1)...

This is main(2)...

This is main(3)[0]...

this is thread 1 [0]...

this is thread 2 [0]...

this is thread 3 [0]...

This is main(3)[1]...

this is thread 1 [1]...

this is thread 2 [1]...

this is thread 3 [1]...

This is main(3)[2]...

this is thread 1 [2]...

this is thread 2 [2]...

this is thread 3 [2]...

This is main(3)[3]...

Thread 1 is done...

*** glibc detected *** ./t1: double free or corruption (!prev): 0x0000000001371b80 ***

======= Backtrace: =========

/lib64/libc.so.6[0x36f1875f4e]

/lib64/libc.so.6[0x36f1878cf0]

./t1[0x40095f]

The expected output should be:

Here's my code:

#include "t_lib.h"
#include <errno.h>

Queue *runningQueue;
Queue *readyQueue;
ucontext_t *newT;
ucontext_t *mainT;
TCB *current;


void t_init()
{
runningQueue = (Queue *)malloc(sizeof(Queue));
readyQueue = (Queue *)malloc(sizeof(Queue));
  
initQueue(runningQueue);
initQueue(readyQueue);
mainT = (ucontext_t *) malloc(sizeof(ucontext_t));

getcontext(mainT); /* let mainT be the context of main thread */

Enqueue(runningQueue,createTCB(mainT,0,1));
}

void t_shutdown()
{
   free(runningQueue);
   free(readyQueue);
   free(mainT);
   free(newT);
   free(current);
}

int t_create(void (*fct)(int), int id, int pri)
{
   size_t size = 0x10000;
   newT = (ucontext_t *) malloc(sizeof(ucontext_t));
  
   getcontext(newT); /* let newT be the context of new thread */
   newT->uc_stack.ss_sp = malloc(size); /* new statement */
newT->uc_stack.ss_size = size;
newT->uc_stack.ss_flags = 0;
newT->uc_link = &runningQueue->front->thread_context;
   makecontext(newT, (void (*)(void)) fct, 1, id);
  
   Enqueue(readyQueue,createTCB(newT,id,pri));
//   setcontext(newT); // switch to new one
}

void t_terminate()
{
   Dequeue(runningQueue);
  
   setcontext(&readyQueue->front->thread_context);
}

void t_yield()
{
   current = (TCB *)malloc(sizeof(TCB));
current = runningQueue->front;
  
   if (readyQueue->front != NULL) {
       Enqueue(readyQueue, current);
       runningQueue->front = readyQueue->front;
       Dequeue(readyQueue);
       swapcontext(&readyQueue->rear->thread_context, &runningQueue->front->thread_context);
}
}

What might be the problem?

Explanation / Answer

I think, in this case concern can be the order in which we are dealloacting or freeing the "runningQueue", "readyQueue", "mainT", "newT" and "current" in the method "void t_shutdown() " . Dealloacting objects order can be checked here.