繁体   English   中英

为什么我在这里遇到细分错误?

[英]Why am I getting a Segmentation Fault here?

#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

pr1prcmd_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);

修改您的主要方法(仅主要方法)为:

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

如果您不告诉我们在哪里,很难告诉您...

  • 您必须将node-> next_prcmd初始化为null
  • 为什么在while循环中使用malloc? 您因此破坏了current-> next,这在下一次迭代中非常糟糕...

马里奥

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM