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 ?
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.
malloc()
et al), your comments are rather tangential to the problem. Clearly, in this context, memory allocation is not being centralized by the run-time library. –
Beadledom 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.
printf
doesn't use malloc
? (On many real systems, it does!) Or any other standard library function? That was the whole point of my answer. "I don't use malloc
" is not a sufficient condition for brk
or sbrk
to be safe to use. Really there is no sufficient condition for them to be safe. –
Unselfish sbrk
. Now, what if one doesn't use any stdlib at all ? or better, a custom stdlib that specifically doesnt use malloc. OR EVEN, a hooked runtime that hacks the malloc function by doing some virtual symbol table redirection into a custom function ? –
Stinkhorn sbrk
safely. In fact I would surmise that the only reason sbrk
is still offered on many modern systems is as a tool for writing custom versions of malloc
, and if that's supported by your system, it's probably the one usage case in which sbrk
is safe (since you can't fight with malloc
if you're the one providing malloc
). –
Unselfish malloc
itself ? which as you say, is legit. So you see "dont't use brk" in your original statement is just too strong. –
Stinkhorn malloc
" or something used in place of malloc
but with a different name and API. In the former case it's probably ok; in the latter it's definitely not. –
Unselfish © 2022 - 2024 — McMap. All rights reserved.
sbrk
, just pass it a negative value. – Woolard