I have only been working with C for a couple of months and I think I have a pretty good function to insert a node in the front of the circular doubly linked list. I have tested in adding several nodes to it, but would like some feedback.
struct
used in functions:
typedef struct TCB_t
{
struct TCB_t * next;
struct TCB_t * previous;
ucontext_t context;
int val;
}TCB_t;
Here is the function that calls the add_to_list()
function:
void start_thread(void (*function)(void), int *arg)
{
printf("In main: creating thread\n");
struct stack * stackP = (struct stack*)malloc(8192);
tcb = (struct TCB_t *)malloc(sizeof(struct TCB_t));
init_TCB (tcb, function, stackP, 8192);
tcb->val = iter;
iter++;
add_to_list( &ptr, &tcb);
}
This is the function in which I am not sure if I am adding the nodes correctly:
void add_to_list( struct TCB_t **ptrBlock, struct TCB_t **addQ)
{
(*addQ)->val = iter;
iter++;
if(!*ptrBlock)
{
*ptrBlock = *addQ;
(*ptrBlock)->next= *ptrBlock;
(*ptrBlock)->previous = *ptrBlock;
}
else
{
(*ptrBlock)->previous->next = *addQ;
(*addQ)->previous = (*ptrBlock)->previous;
(*addQ)->next = *ptrBlock;
(*ptrBlock)->previous = *addQ;
}
}
struct TCB_t
, and ideally, some complete but short test code, for better reviews. \$\endgroup\$add_to_list
takesTCB_t **addQ
as an argument instead of justTCB_t *addQ
. You never modify the actual pointer passed in, so you are just adding a level of indirection for nothing. Also I personally like to use a local variablep
which is set to*ptrBlock
and then usep
to do the list manipulation, then at the end set*ptrBlock = p
. It gets rid of all the awkward(*ptrBlock)
s. \$\endgroup\$