问题描述
我重新编码了malloc()
free()
和realloc()
.
我有一个链接列表,其中包含malloc()
返回的指针.
I have a linked list with the pointers returned by malloc()
.
问题是:free()
的真正作用是什么?
The question is : what does free()
really do ?
当前,我做了memset()
以具有与free()
相同的行为.
Currently, I did a memset()
to have the same behavior of free()
.
但是,将列表中的标志设置为免费"比执行memset()
更快是不是更好呢?
But was it better just to set a flag in my list as 'is free' rather than doing a memset()
in order to make it faster ?
推荐答案
通常,free(3)对内存本身不做任何事情. (如果需要考虑安全性或隐私权,则应在释放之前清除内存.)
Usually free(3) does not do anything to the memory itself. (If security or privacy is a concern, you should clear memory before freeing.)
如果要实现malloc,则需要具有一些可用内存块的数据库.释放内存后,您应该将其与伴随的空闲内存(如果有的话)一起加入.如果一个完整的页面最终没有被使用,您应该告诉内核,您不再需要它(取决于您首先获得该内存的方式)
If you want to implement malloc, you need to have some database of free memory blocks. When memory is freed you should join it with adjoint free memory, if there is any. If a complete page ends up unused, you should tell the kernel, that you don't need it anymore (depending on how you got that memory in the first place)
这篇关于C-free()对内存有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!