#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <stdlib.h>
typedef struct pr_struct{
int owner;
int burst_time;
struct pr_struct *next_prcmd;
} prcmd_t;
static prcmd_t *pr_head = NULL;
static prcmd_t *pr_tail = NULL;
static int pending_request = 0;
static pthread_mutex_t prmutex = PTHREAD_MUTEX_INITIALIZER;
int add_queue(prcmd_t *node)
{
pthread_mutex_lock(&prmutex);
//code
prcmd_t *curNode = pr_head;
if(pr_head == NULL) { pr_head = node; return;}
while(curNode->next_prcmd)
{
curNode->next_prcmd = (prcmd_t*)malloc(sizeof(prcmd_t));
curNode = curNode->next_prcmd;
}
curNode->next_prcmd = node;
//
pending_request++;
pthread_mutex_unlock(&prmutex);
return(0);
}
int main()
{
if (pr_head == NULL)
{
printf("List is empty!\n");
}
prcmd_t *pr1;
pr1->owner = 1;
pr1->burst_time = 10;
add_queue(pr1);
prcmd_t *curNode = pr_head;
while(curNode->next_prcmd)
{
printf("%i\n", curNode->owner);
curNode = curNode->next_prcmd;
}
}
编辑:
这就是我现在所拥有的......
int main()
{
prcmd_t *pr1;
pr1 = (prcmd_t*)malloc(sizeof(prcmd_t));
pr1->owner = 1;
pr1->burst_time = 10;
if (pr_head == NULL)
{
printf("List is empty!\n");
}
add_queue(pr1);
prcmd_t *curNode = pr_head;
printf("made it here 1\n");
while(curNode->next_prcmd)
{
printf("in the while loop\n");
printf("%i\n", curNode->owner);
curNode = curNode->next_prcmd;
}
}
输出是: 清单是空的! 在这里做了1
答案 0 :(得分:4)
pr1
是指向prcmd_t struct
的未初始化指针,取消引用未初始化的指针导致undefined behavior。
您需要为堆/堆栈上的结构分配空间(取决于它将被使用的位置),因此一个选项是:
// Allocate on stack
prcmd_t pr1;
pr1.owner = 1;
pr1.burst_time = 10;
add_queue(&pr1);
,第二是:
//Allocae on heap
prcmd_t *pr1;
pr = (prcmd_t*)malloc(sizeof(prcmd_t));
pr1->owner = 1;
pr1->burst_time = 10;
add_queue(pr1);
将主要方法(仅限主要方法)修改为:
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;
}
}
输出
List is empty!
1
答案 1 :(得分:2)
如果没有你电话我们在哪里......很难说。
但是
马里奥