【问题标题】:get heap-use-after-free in Leetcode在 Leetcode 中获取 heap-use-after-free
【发布时间】:2022-11-21 12:12:44
【问题描述】:

我有一个 Leetcode 问题,No.142,Linked List Cycle II。我的代码就像这样:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *detectCycle(struct ListNode *head) {

    struct ListNode *flag = (struct ListNode *)malloc(sizeof(struct ListNode));
    int count = 0;

    while (head != NULL) {

        if (head -> next == flag) {
            free(flag);
            return head -> val;
        }

        head -> val = count;
        ++count;

        struct ListNode *p = head;
        head = head -> next;
        p -> next = flag;

    }

    free(flag);
    return -1;

}

运行后,出现释放后堆使用错误。我该如何解决?

【问题讨论】:

  • 检查完每个节点后,我会将其 NEXT 更改为 FLAG,将 VAL 更改为索引(也包括计数)。如果有循环,head -> next会是FLAG。在那种情况下,我可以返回 val。

标签: c malloc heap-memory free


【解决方案1】:

只需在标志可用之前使用临时变量存储 head->val,然后返回 val,请参见下面的代码。

if (head -> next == flag) {
    int val = head->val;    
    free(flag);
    return val;
}

您的代码中只有两个地方可以释放内存。 我只是在解决您遇到的错误。我将通过执行以下操作修改代码以具有单个 return & free 语句:

  int returnVal = -1;
  while loop  {

   if (head -> next == flag) {
    returnVal = head->val;
     break;     //exit while loop
   } else  {

     .
     .
     .
 
   }
}     // end while
free(flag);
return returnVal;

【讨论】:

  • 它不起作用。标志是节点的成员。我释放了标志,但没有释放节点。
猜你喜欢
  • 2019-08-03
  • 2020-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-08
  • 1970-01-01
  • 1970-01-01
  • 2020-11-21
相关资源
最近更新 更多