#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("%in", 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 1n");
while(curNode->next_prcmd)
{
printf("in the while loopn");
printf("%in", curNode->owner);
curNode = curNode->next_prcmd;
}
}
输出是:列表为空!1
pr1
是指向prcmd_t struct
的未初始化指针,解引用未初始化的指针会导致未定义行为。
你需要在堆/堆栈上为结构分配空间(取决于它将被使用的位置),所以一个选项是:
// 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);
将你的main方法修改为
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("%in", curNode->owner);
curNode = curNode->next_prcmd;
}
}
输出List is empty!
1
如果你不告诉我们在哪里,我们很难判断…
,
- 必须初始化节点->next_prcmd为null 为什么在while循环中使用malloc ?你是从而摧毁你的当前->下一个,下一个迭代哪个好看坏…