使用一个命令释放所有malloc() - 创建的指针?

时间:2010-02-20 18:10:40

标签: c free malloc

是否有一个单行代码可以释放使用malloc s创建的所有指针所占用的内存?或者这只能通过单独free每个指针手动完成吗?

6 个答案:

答案 0 :(得分:6)

你可以通过在malloc周围创建某种“包装器”来做到这一点。 (警告说只有伪代码显示了这个想法,根本没有检查)

void* your_malloc(size_t size)
{
    void* ptr = malloc(size);

    // add ptr to a list of allocated ptrs here

    return ptr;
}

void your_free(void *pointer)
{
    for each pointer in your list
    {
        free( ptr_in_your_list );
    }
}

但这听起来不是一个好主意,我肯定不会这样做,至少对于通用分配/解除分配。当不再需要时,你最好负责任地分配和释放内存。

答案 1 :(得分:3)

您可能需要查看memory pools。这些数据结构正是为此而构建的。

一个常见的实现是在Apache Portable Runtime中,它在Apache Web服务器中使用,以及其他项目,如Subversion。

答案 2 :(得分:2)

malloc对它自己有实现定义的行为。所以没有必要跟踪它所有的指针,这显然会阻碍这个想法。

您需要创建自己的内存管理器来跟踪指针,然后提供一个名为free_all的函数或者通过它所拥有的指针列表并在其上调用free的函数。

请注意,这听起来有点糟糕。最好对你的内存使用更加严格/负责,并在你完成后free事情;不要让他们闲逛。

或许有更多关于你想要应用想法的背景知识,我们可能会找到更简单的解决方案。

答案 3 :(得分:1)

查看dlmalloc

ftp://g.oswego.edu/pub/misc/malloc.h

查看以下功能

/*
  mspace is an opaque type representing an independent
  region of space that supports mspace_malloc, etc.
*/
typedef void* mspace;

/*
  create_mspace creates and returns a new independent space with the
  given initial capacity, or, if 0, the default granularity size.  It
  returns null if there is no system memory available to create the
  space.  If argument locked is non-zero, the space uses a separate
  lock to control access. The capacity of the space will grow
  dynamically as needed to service mspace_malloc requests.  You can
  control the sizes of incremental increases of this space by
  compiling with a different DEFAULT_GRANULARITY or dynamically
  setting with mallopt(M_GRANULARITY, value).
*/
mspace create_mspace(size_t capacity, int locked);

/*
  destroy_mspace destroys the given space, and attempts to return all
  of its memory back to the system, returning the total number of
  bytes freed. After destruction, the results of access to all memory
  used by the space become undefined.
*/
size_t destroy_mspace(mspace msp);

...

/*
  The following operate identically to their malloc counterparts
  but operate only for the given mspace argument
*/
void* mspace_malloc(mspace msp, size_t bytes);
void mspace_free(mspace msp, void* mem);
void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size);
void* mspace_realloc(mspace msp, void* mem, size_t newsize);

答案 4 :(得分:0)

您可能想要做一些名为“竞技场分配”的事情,您可以从共同的“竞技场”中分配某些请求,这些请求可以在您完成时立即释放。

如果您使用的是Windows,则可以使用HeapCreate创建竞技场,使用HeapAlloc从刚刚创建的堆/竞技场获取内存,使用HeapDestroy立即释放它。

请注意,当您的程序退出()时,释放您使用malloc()分配的所有内存。

答案 5 :(得分:0)

是的,除非您自己定义malloc()free(),否则可以这样做。您应该调用myCustomMalloc()而不是常规malloc(),并且您应该跟踪某些内存位置中的所有指针,并且当您调用myCustomFree()方法时,您应该能够清除所有内容使用myCustomMalloc()创建的指针。注意:您的自定义方法都将在内部调用malloc()free()

通过这种方式,您可以实现目标。我是一个java人,但我早年在C中工作很多。我假设您正在尝试实现编译器正在处理内存的通用解决方案。如Java中所见,这会带来性能成本。你不必担心分配和释放内存。但这对性能有严重影响。这是你必须要做的权衡。