c - 为什么我在这里遇到段错误?

标签 c unix linked-list

#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

最佳答案

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

将您的 main 方法(且仅是 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("%i\n", curNode->owner);
        curNode = curNode->next_prcmd;
    }
}

输出

List is empty!
1

关于c - 为什么我在这里遇到段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5906741/

相关文章:

c - 如何计算文件中的换行符,但不计算只是换行符的行?

oracle - 在 makefile 中设置动态 ORACLE_HOME

java - 为什么需要(LinkedList)?

c++ - C - 正在使用变量 'p_prvy' 而未初始化

c - 以编程方式更改 "Advanced TCP/IP Settings"- 正在检查 "Use Default Gate Way on Remote Network"

c - 奇怪/简单的 C 错误

c - 填充表格顶部的函数

c - 将长时间运行的子进程的输出重定向到父进程

linux - 如何找出进程正在使用的端口号

c++ - 链接列表 (C/C++)。同时创建列表结构和节点结构有哪些优点/缺点?