Why am I getting a Segmentation Fault here? Why am I getting a Segmentation Fault here? unix unix

Why am I getting a Segmentation Fault here?


pr1 is an uninitialized pointer to prcmd_t struct, dereferencing uninitialized pointer causes undefined behavior.

You need to allocate space for the structure on the heap / stack (depending on where it's gonna be used), so one option is:

// Allocate on stackprcmd_t pr1;pr1.owner = 1;pr1.burst_time = 10;add_queue(&pr1);

and second is:

//Allocae on heapprcmd_t *pr1;pr = (prcmd_t*)malloc(sizeof(prcmd_t));pr1->owner = 1;pr1->burst_time = 10;add_queue(pr1);

Modifying your main method (and main only) to:

int main(){    if (pr_head == NULL)    {        printf("List is empty!\n");    }    prcmd_t *pr1;       pr1 = (prcmd_t*)malloc(sizeof(prcmd_t));    pr1->owner = 1;    pr1->burst_time = 10;    add_queue(pr1);    prcmd_t *curNode = pr_head;    while(curNode && curNode->owner)    {        printf("%i\n", curNode->owner);        curNode = curNode->next_prcmd;    }}

Outputs

List is empty!1


It's hard to tell without you tellung us where...

But

  • you have to initializenode->next_prcmd to null
  • why do you malloc in the while loop? you arethereby destroing your current->next,which in the next iteration is prettybad...

Mario