C - What does free() do to the memory?

不羁的心 提交于 2019-12-13 02:35:01

问题


I recoded malloc() free() and realloc().

I have a linked list with the pointers returned by malloc().

The question is : what does free() really do ?

Currently, I did a memset() to have the same behavior of free().

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 ?


回答1:


Usually free(3) does not do anything to the memory itself. (If security or privacy is a concern, you should clear memory before freeing.)

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)




回答2:


The C library function void free(void *ptr) deallocates the memory previously allocated by a call to calloc, malloc, or realloc.

You should use it to prevent memory leaks.




回答3:


Free : Call will unlink / unallocate the memory pointed by pointer so that other process can use it.

Memset : Call will set a memory / fill a memory location. It won't unlink / unallocate a memory and memory remain allocated / occupied till the program exist. Which can cause memory leaks.

You can use valgrind tool to check memory leaks.

And it is a better practice to unlink / unallocate a memory if its not required.



来源:https://stackoverflow.com/questions/28454123/c-what-does-free-do-to-the-memory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!