alloclen which returned the length of a memory allocation? That could simplify some parameter-passing!#CLanguage
alloclen which returned the length of a memory allocation? That could simplify some parameter-passing!By the way, if you're programming on plan9 you've been able to do this for decades:
extern ulong poolmsize(Pool*, void*);
you can just run `poolmsize(mainmem, alloc)` to get the size of an allocation that was malloced (since malloc gores through the mainmem pool)
What about stack allocations though?
e.g.
char foo[10];
bar(&foo, 10)
? You'd still have footguns now because you have inconsistent behavior for stack/heap, or you only support one, or...
free(p_param) in this void bar(char *p_param) wouldn't work in either case, as bar would need to know that the p_param pointer points to malloc'd data, right? alloclen would only work with pointers which came from malloc, same as with free and realloc and such.No no, it's not about deallocations or frees at all
If I have a function that takes `(void *foo, usize foolen)`, it can take in storage from anywhere: stack, heap, mmap, it doesn't matter.
If you change it to just (void *foo) and assume you can use alloclen(foo), then the pattern in my original post becomes invalid
The following is valid C using a real API on plan 9 that will not do the right thing:
#include <pool.h>
void bar(char *foo);
char foo[10];
bar(&foo);
void
bar(char *foo)
{
int len = poolmsize(mainmem, foo);
// if foo is on the heap, len is the CAPACITY of the allocation
// given foo = malloc(15), len is guaranteed to be AT LEAST 15
// It may well be 16 or 30 or 100
// If foo is NOT on the heap,
// the result will be either nonsense or a segfault
// The only possible implementations are
// a) Assume on the heap, and give possibly invalid results, or
// b) Check if on the heap, and either crash or return -1 or etc
// There is no world in which this does the right thing for the stack unless stack allocation lengths are stored somewhere by the compiler etc
}
@golemwire I mean, no, I actually agree that C could benefit a lot from slices in the language. It's a super simple thing, could be added to the compiler easily, and it would allow for exactly this, because it's just sugar for the direct passing anyways!
void bar(char *foo, int foolen);
void bar2(char[:] foo);
...
char foo[10];
bar(&foo, 10);
bar(foo+4, 6);
bar2(foo[4:]);
It's still explicit human tracking, not language/runtime, it's just a nicer way of passing this info around
(And once you HAVE a slice, it does provide a bit of extra safety: you can't subslice beyond the limits, etc)