views:

342

answers:

2

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 ?

+7  A: 

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.

Arkaitz Jimenez
-1, you can decrease with `sbrk`, just pass it a negative value.
avakar
You are right, I'll edit it. Never used sbrk like that, cool.
Arkaitz Jimenez
Great, I've removed the downvote.
avakar
The only thing to worry about is whether something other than your code called 'sbrk()' and got memory and that your adjustment downwards invalidates memory that something else is still using.
Jonathan Leffler
+1  A: 

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.

R..