【发布时间】:2021-10-17 01:10:03
【问题描述】:
我正在使用 C 实现一个单链表。
struct Node
{
int nodeValue;
struct Node* pNext;
};
struct Node* head;
void createList()
{
head = (struct Node*)malloc(sizeof(struct Node));
}
void insertNodeAtBeginning(int value)
{
struct Node* newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->nodeValue = value;
struct Node* auxNode;
if(head->pNext == NULL)
{
head->pNext = newNode;
}
else
{
auxNode = head->pNext;
head->pNext = newNode;
newNode->pNext = auxNode; //breakpoint set here
}
}
我已经在注释标记的行上设置了一个断点。 auxNode 的值为非NULL:
(gdb) p auxNode
$4 = (struct Node *) 0x5555555551db <createList+18>
但是,分配了auxNode的newNode->pNext的值为NULL:
(gdb) p newNode->pNext
$5 = (struct Node *) 0x0
谁能澄清这种行为?谢谢。
【问题讨论】:
-
如果您在该行停止,则该行尚未执行。
step运行该行,然后再次检查值。 -
(a) 编辑问题以提供minimal reproducible example。 (b)
createList为一个节点分配空间并将head设置为指向它,但不填充该空间,也没有显示任何其他代码。insertNodeAtBeginning可能正在使用未初始化的空间内容。 (c) 当代码在newNode->pNext = auxNode行中断时,该行还没有被执行。 -
head->pNext未在createList中初始化
标签: c pointers linked-list singly-linked-list function-definition