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

标签 c pointers linked-list queue

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

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/

相关文章:

objective-c - 在 Objective C 类中使用静态 c 变量

c - 插入链表

c - 边的链接列表

java - Java中递归地反转链表

c - 用于绘制特定变量事件图的公式

检查输入是否存在可能的 Int 溢出

c - C中指向数组的指针

c - 分割字符串函数的段错误

c - 如何计算字典中单词中前两个字母的出现频率?

c - 正确检索 C 结构中的指针字段