gpt4 book ai didi

c - 为什么 `pLQ->tail`是空指针?

转载 作者:行者123 更新时间:2023-11-30 16:25:50 25 4
gpt4 key购买 nike

我正在处理一个队列,但一直遇到排队问题。这是我认为相关的代码:

typedef struct Qnode QNODE;
struct Qnode
{
int length;
QNODE* next;
QNODE* prev;
};

typedef struct lqueue lQUEUE;
struct lqueue
{
QNODE *head;
QNODE *tail;
};

lQueue lqueue_init_default(void)
{
lQUEUE* pQ = NULL;
pQ = (lQUEUE*)malloc(sizeof(lQUEUE));
if (pQ != NULL)
{
pQ->head = NULL;
pQ->tail = NULL;
}
pQ->head = pQ->tail;
return pQ;
}

Status lqueue_henqueue(lQueue* hLQ, int lc)
{
lQUEUE* pLQ = (lQUEUE*)hLQ;
QNODE* new = (QNODE*)malloc(sizeof(QNODE));
if (new == NULL)
{
printf("Couldn't allocate space.\n");
return FAILURE;
}
new->length = lc;
new->next = pLQ->tail->next;

pLQ->tail = new;
return SUCCESS;
}

每当我尝试运行该程序时,我都会在运行时收到此错误:
抛出异常:读取访问冲突。pLQ->tail 为 nullptr。
为什么是空指针?和初始化函数有关系吗?
其名称如下:

int cl = 0;//Individual car length
lQueue hLQ = lqueue_init_default();//Handle to the left queue
printf("Enter the length of the lcar:\n");
scanf("%d", &cl);
lqueue_henqueue(hLQ, cl);

最佳答案

您的代码很容易出现 undefined behavior ...看看这个 if 语句:

if (pQ != NULL)
{
pQ->head = NULL; // This pointer is now 'NULL'
pQ->tail = NULL; // This is also 'NULL'
}

哪个应该这个...

if (pQ != NULL)
{
pQ->head = (QNODE*)calloc(1, sizeof(lQUEUE)); // This is proper pointer initialization...
pQ->tail = (QNODE*)calloc(1, sizeof(lQUEUE));
}

还有这个:

lQueue lqueue_init_default(void)

应该是这样的:

lQueue * lqueue_init_default(void) // Since you are returning a pointer...

您将看到代码工作正常,因为没有未定义的行为...

Note that you can never access an object that is assigned to NULL... (Only if you don't want your program to behave undefined...) So, this:

pQ->tail = NULL;

is not safe in the very least... Structural pointers being assigned to NULL are usually only seen when being destroyed... An example is given below...

<小时/>

此外,不相关,但是为该结构提供一个析构函数,并在不再需要该结构时调用它,否则它会之后泄漏内存...

void destroy_lqueue(struct lqueue ** queue)
{
if (queue != NULL)
queue = NULL;
free(queue);
}

关于c - 为什么 `pLQ->tail`是空指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53245852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com