2

是否有一种方法可以释放您使用mallocs 创建的所有指针所占用的内存?或者这只能通过free单独设置每个指针来手动完成?

4

6 回答 6

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

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

于 2010-02-20T18:19:51.833 回答
3

您可能想查看内存池。这些数据结构正是为此而构建的。

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

于 2010-02-20T18:23:15.633 回答
2

malloc它本身具有实现定义的行为。因此,它没有必要跟踪它拥有的所有指针,这显然阻碍了这个想法。

您需要创建自己的内存管理器来跟踪指针,然后提供一个调用的函数free_all或遍历它拥有的指针列表并调用free它们的东西。

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

也许有了更多关于您想在哪里应用您的想法的背景知识,我们可能会找到更简单的解决方案。

于 2010-02-20T18:14:37.870 回答
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);
于 2016-06-17T16:52:46.380 回答
0

您可能想做一些称为“竞技场分配”的事情,您可以在其中分配来自公共“竞技场”的某些请求,这些请求可以在完成后立即释放。

如果您在 Windows 上,您可以使用 HeapCreate 创建一个 arena,使用 HeapAlloc 从您刚刚创建的堆/arena 中获取内存,并使用 HeapDestroy 一次性释放所有内存。

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

于 2010-02-20T18:21:07.103 回答
0

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

通过这种方式,您可以实现您的目标。我是一个 java 人,但我在早期经常使用 C 语言工作。我假设您正在尝试实现一个由编译器处理内存的通用解决方案。正如在 Java 中所看到的那样,这具有性能成本。您不必担心分配和释放内存。但这会对性能产生严重影响。这是你必须忍受的权衡。

于 2010-02-20T18:21:34.187 回答