- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在处理一个队列,但一直遇到排队问题。这是我认为相关的代码:
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/
我正在处理一个队列,但一直遇到排队问题。这是我认为相关的代码: typedef struct Qnode QNODE; struct Qnode { int length; QNODE* ne
我是一名优秀的程序员,十分优秀!