【问题标题】:Why is "free" saying this that my pointer is invalid?为什么“免费”说我的指针无效?
【发布时间】:2021-12-31 09:59:30
【问题描述】:
while(n >= 0);
    node * point = malloc(sizeof(node));
    point = create(number, n);

    //show(point);

    //free memory
    while(point != NULL)
    {
        node *tmp = point->next;
        free(point);
        point = tmp;
    }

}

node * create(int data[], int len)
{
    node * list_head;
    node * list;
    for (int i = 0; i < len; i++)
    {
        if(i == 0)
        {
            list_head = malloc(sizeof(node));
            list = malloc(sizeof(node));
            list_head->value = data[0];
            list_head->next = list;
        }
        else
        {
            list->value = data[i];
            list->next = malloc(sizeof(node));
            list->next = NULL;
        }
    }
    return list_head;
}

此代码返回的错误是:- free(): invalid pointer 中止 |为什么我的代码没有释放我分配的内存。是不是因为我在一些不同的功能中分配了它?

【问题讨论】:

  • 仅供参考,C 指针不是 Java 或 C# 引用。这段代码像疯了一样泄漏内存。
  • while(n &gt;= 0); 看起来像无限循环或无操作
  • 这两行有list-&gt;next = malloc(sizeof(node)); list-&gt;next = NULL;表示错误
  • 除其他错误外,分配list时,并没有对其进行初始化。所以最后的 ->next 总是不确定的。

标签: c pointers linked-list


【解决方案1】:

你贴的代码应该改成:

while(n >= 0) {
    node * point = create(number, n);

和:

list->next = NULL;

应该改为

list = list->next;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-20
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 2012-07-23
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多