需要显式调用 free() 的 C 函数
C functions requiring explicit call to free()
我想知道所有在内部使用 malloc() 的 C 标准函数和 returns 指向新分配的内存块的指针。据我所知有:
- strdup()
- getcwd()
- get_current_dir_name()
是吗?我正在编写一个复杂的解析器,它将所有 C 原始指针更改为更精细的 C++ 智能指针,我需要知道在哪些地方无法自动完成此操作。
名单是:
malloc
calloc
realloc
aligned_alloc
(C11 新增)
None 你列出的函数是标准的 C。
您的列表相当正确,但是 strdup
和 getcwd
是 POSIX(在 C99 中未标准化),get_current_dir_name
是 GNU(甚至 POSIX).
您会发现其他函数返回一些堆分配的数据。
但是您总是应该在使用某些函数之前阅读它的文档。它会告诉你返回值是否是堆分配的(以及应该释放谁以及如何释放)。
有些函数获取指针地址并可能更改它。例如 getline(3) (POSIX) or asprintf(3) or open_memstream(3)(有些分配甚至可能发生在 之后 )。
顺便说一句,像 fopen
这样的一些标准函数可能正在使用堆分配的内存(在 fclose
时被释放)。
同样,对于您自己的库,将它们记录得足够好,以明确指出谁负责 free
-in g(或以其他方式销毁)每个堆分配的指针。即使是您自己的私有函数,也请在评论中记录下来。
自动检测与动态堆内存分配相关的函数很困难,并且在一般情况下不可能可靠地完成(参见 Rice's theorem),因此进行了一个有趣的研究项目。
Allocates a block of size bytes of memory, returning a pointer to the beginning of the block.
Changes the size of the memory block pointed to by ptr.
Allocates a block of memory for an array of num elements, each of them size bytes long, and initializes all its bits to zero.
我想知道所有在内部使用 malloc() 的 C 标准函数和 returns 指向新分配的内存块的指针。据我所知有:
- strdup()
- getcwd()
- get_current_dir_name()
是吗?我正在编写一个复杂的解析器,它将所有 C 原始指针更改为更精细的 C++ 智能指针,我需要知道在哪些地方无法自动完成此操作。
名单是:
malloc
calloc
realloc
aligned_alloc
(C11 新增)
None 你列出的函数是标准的 C。
您的列表相当正确,但是 strdup
和 getcwd
是 POSIX(在 C99 中未标准化),get_current_dir_name
是 GNU(甚至 POSIX).
您会发现其他函数返回一些堆分配的数据。
但是您总是应该在使用某些函数之前阅读它的文档。它会告诉你返回值是否是堆分配的(以及应该释放谁以及如何释放)。
有些函数获取指针地址并可能更改它。例如 getline(3) (POSIX) or asprintf(3) or open_memstream(3)(有些分配甚至可能发生在 之后 )。
顺便说一句,像 fopen
这样的一些标准函数可能正在使用堆分配的内存(在 fclose
时被释放)。
同样,对于您自己的库,将它们记录得足够好,以明确指出谁负责 free
-in g(或以其他方式销毁)每个堆分配的指针。即使是您自己的私有函数,也请在评论中记录下来。
自动检测与动态堆内存分配相关的函数很困难,并且在一般情况下不可能可靠地完成(参见 Rice's theorem),因此进行了一个有趣的研究项目。
Allocates a block of size bytes of memory, returning a pointer to the beginning of the block.
Changes the size of the memory block pointed to by ptr.
Allocates a block of memory for an array of num elements, each of them size bytes long, and initializes all its bits to zero.