假设 malloc 成功,这段代码中可能存在哪些与内存相关的潜在问题?

问题描述 投票:0回答:1

考虑以下代码片段,用于在单链表的末尾插入节点。假设 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;
}
  1. 由于 temp->next = new_node 的分配不正确,导致指针访问无效。
  2. 由于内存中不存在 temp->next 导致分段错误。
  3. 由于在插入 new_node 后未释放头而导致内存泄漏。
  4. 由于 head 为 NULL 导致分段错误。
  5. malloc 中参数使用不当导致内存错误。
  6. 对于非空情况,链表的头并不总是正确的。

这个问题的正确答案,因为有一个问题,没有正确答案

c
1个回答
0
投票

由于 head 为 NULL 导致分段错误。

如果我像这样调用该函数:

insertEnd(NULL, 5);

线路

if (*head == NULL) {

尝试取消引用

NULL
指针。接下来发生的是未定义的行为,但是,在现代操作系统上,很可能会以暴力偏见终止程序。

© www.soinside.com 2019 - 2024. All rights reserved.