考虑以下代码片段,用于在单链表的末尾插入节点。假设 malloc 成功,这段代码中可能存在哪些与内存相关的潜在问题?
struct Node {
int value;
struct Node* next;
};
void insertEnd(struct Node** head, int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
return;
}
struct Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
这个问题的正确答案,因为有一个问题,没有正确答案
由于 head 为 NULL 导致分段错误。
如果我像这样调用该函数:
insertEnd(NULL, 5);
线路
if (*head == NULL) {
尝试取消引用
NULL
指针。接下来发生的是未定义的行为,但是,在现代操作系统上,很可能会以暴力偏见终止程序。