结构数组 - C中的内存释放

时间:2013-08-19 10:37:18

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

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

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]);

我正在获取指针被释放错误。这是正确的实施方式吗?如何解决内存问题?

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

2 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:1)

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

例如:

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));