【问题标题】:Array of structure - memory release in C结构数组 - C 中的内存释放
【发布时间】:2013-08-19 10:37:17
【问题描述】:

我正在尝试使用静态数组实现基于二进制堆的优先级队列(稍后我将使用链表,只是想先用数组进行测试)。

typedef struct n
{
    int x;
    int y;
    int size;
    double value;
} node;

node arr[100];
int total = 1;

void insertElement(int x, int y, int size, double value)
{
    node n;
    n.x     = x;
    n.y     = y;
    n.size  = size;
    n.value = value;

    arr[total] = n;

    if (total > 1)
        insertArrange(total);

    total += 1;
}

现在在删除函数中,我将只返回最顶层的节点并将其删除,然后重新排列整个堆。问题是我无法释放任何内存。假设我使用

free(&arr[1]);

我收到指针未分配错误。这是正确的实施方式吗?如何解决内存问题?

我将 Xcode 与 Apple LLVM 4.2 编译器一起使用。整个事情最终将被放入一个更大的 Objective-C 项目中,但现在我不想使用 NSMutableArray。我想要一个简单的 C 语言解决方案。

【问题讨论】:

  • 你不会释放这样声明的int。为什么要免费node
  • 抱歉那一行是 free(&arr[1]) 导致我上面提到的错误。

标签: c memory-management data-structures struct priority-queue


【解决方案1】:

如果你使用过 malloc() 或 calloc(),你只需要调用 free()。事实上,试图释放其他东西是未定义的行为

就目前而言,您的代码不会泄漏任何内存。

【讨论】:

  • 好的,我明白你的意思。你能告诉我如何实现删除功能吗?只需返回第一个元素,然后将其删除。 (堆的其余部分保持完整 - 我稍后会重新排列。)
  • @Soumyajit, arr[] 是堆栈分配的;您不得尝试删除任何记忆。
【解决方案2】:

为什么要删除?您可以将其归零并在需要时向其写入新数据。另外我的建议是记住你删除了哪些节点,这样以后当你需要插入一个新节点时,你就会事先知道空闲空间在哪里。

例如:

node arr[10];
indexes free_index[10];
//(delete the 6th member of nodes)
delete arr[5];
//remember which one you deleted
free_index[0] = 5;
//later when you add new node you can search the index and pick the first matching value
// zero it out so that it will not be used accidentally again like this
int i = free_index[0] // finding which one is free is task for loops
new_node(arr[i]);
free_index[i] = NULL;

这里的代码示例非常不完整,您必须根据自己的实现来完成它。我只是给你的想法。注意free_index [0] = 0;它基本上永远不会匹配为有效索引。如果你用 = NULL 语句清零索引。

我这边还有一个很大的假设,即您不希望缩小或扩大此数组的大小。只需清空一些元素,然后添加新元素。

如果你想扩大阵列,你必须先calloc 它。我建议 calloc 因为你可以用它分配结构数组。

使用realloc 可以轻松实现这一目标。

但是随着缩小,您需要创建临时节点数组,您将在其中存储所有活动结果,缩小原始数组,将临时数组中的活动结果放回原始和空闲临时数组。

calloc(numberofnodearrays,sizeof(node));

【讨论】:

  • 谢谢,我将使用 calloc 和 realloc 来实现这个。但是根据您的假设,我将它用于优先级队列并假设我删除了顶部(删除将始终是最高优先级),数组大小会缩小。另一件需要注意的事情是,所有的插入都将首先完成,然后逐个删除,所以我只会想出一个解决方法,比如让那个元素变成负数等等。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-07
  • 1970-01-01
  • 2021-08-26
  • 1970-01-01
  • 1970-01-01
  • 2017-06-04
相关资源
最近更新 更多