I have a custom allocator function which uses sbrk() to obtain memory. How do I release this memory when it's no longer needed?
Is there a function equivalent to free() for malloc() ?
or do I have to use brk() to set the end of the data segment ?
You need to use brk
or sbrk
again to shrink.
In the end the only way you have to modify the amount of memory(apart from mmap like syscalls), is to increase or decrease the heap, so you move it up with sbrk
or brk
and you move it down with brk
or sbrk
with a negative increment.
Don't use brk
and sbrk
. It's pretty much impossible to know which library functions might call malloc
, and could change over time, so even if your program works now, it might break when somebody upgrades libc. They were excluded from POSIX for a very good reason.
来源:https://stackoverflow.com/questions/2051994/how-do-i-free-memory-obtained-by-sbrk