by Annatar · 10y ago · 0 comments
That said, there are other ways to avoid writing "free" than using a garbage collector. Regions (https://en.wikipedia.org/wiki/Region-based_memory_management) are faster at allocation than malloc (you just increment a pointer to allocate) and faster at freeing than a GC (you throw away the entire region when you're done with it). It seems tricky to base a general-purpose programming language around them, though.
That is precisely why I mentioned alloca(3C): it automatically frees the memory for you, if you do not want to do it yourself. From the Solaris / illumos alloca(3C) manual page:
void *alloca(size_t size);
The alloca() function allocates size bytes of space in the
stack frame of the caller, and returns a pointer to the
allocated block. This temporary space is automatically freed
when the caller returns. If the allocated block is beyond
the current stack limit, the resulting behavior is unde-
fined.
> (have you ever tried writing a functional program with explicit malloc and free?)I got my start on MOS 6502 / MOS 6510 / MC68000 assembler, so for me making malloc(3C) and free(3C) calls when programming in a functional style is completely normal. I have no problem with that whatsoever.
Did you write your 6502 code with closures, higher-order functions, and so on? My point is that can be hard to figure out when to free an object in this kind of environment, where a value can be captured by multiple closures and may not have a clear owner.
If the allocated block is beyond
the current stack limit, the resulting behavior is unde-
fined.
And you even quoted the part that hints at why alloca(3C) is so rarely used in practice: you get a pointer result, but you have no way of knowing if it's actually safe to use it. #include <sys/time.h>
#include <sys/resource.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
struct rlimit limit;
getrlimit(RLIMIT_STACK, &limit);
printf("Stack start at %p, end at %p.\n", &argc, &argc - limit.rlim_cur);
return(0);
}
% cc limit.c -o limit && ./limit
Stack start at 0x7fff51094ba8, end at 0x7fff4f094ba8.
If the pointer returned by alloca(3C) is within those memory addresses, and does not exceed the bottom (in this example, $7fff4f094ba8), it is safe to use.GC languages require a certain amount of extra memory beyond the live memory as an overhead, but beyond that they should not have more impact on the memory footprint. In some use cases, this extra memory is not acceptable, but for reasonably sized applications, this is acceptable (not talking about Java here...) and the benefit is the correctness and often cleaner code (no complex protocols for object lifetime).