4 ms·
That's true, although there's no reason the stack allocator couldn't record this information somewhere as well. And if the memory allocator doesn't know about
by admax88q 9y ago
That's true, although there's no reason the stack allocator couldn't record this information somewhere as well.
And if the memory allocator doesn't know about the string then you could just revert to the existing behaviour so you're no worse off.
- chrisseaton 9y agoThere's more ways to allocate memory than the heap and stack.
- stochastic_monk 9y agoWhat are you referring to? sbrk? mmap? I typically use either the heap or the stack myself.
- timClicks 9y agoStatic memory is at the bottom of the address space, below the heap. But that would really only be relevant in the case of string literals unless I'm mistaken.
- unwind 9y agoYou can have a static buffer: static char buf[128]; and use strcpy() at any point to copy into it, so I don't think statically allocated strings must be literals.
- stochastic_monk 9y agoThere is a distinction between const and non-const static memory, though, in that the former can be stored in Read-Only Memory. Still, static memory is generally used for many fewer purposes than the stack or the heap, and if I understand correctly, sbrk is still working with the heap, just more manually.
- timClicks 9y agoThat's right. Allocators use the sbrk and mmap to manage the heap. IIRC high performance allocators tend to use mmap exclusively.
- MarceColl 9y agoSomething like memory pools or manual memory management. Yes the memory pool will come from the heap or stack but the heap/stack allocator will have no idea what is going on in there.
- adrianmonk 9y agoAnd all of them know how much memory they've allocated.
- MarceColl 9y agoYes, but unless you expose at the language level an interface for all types of allocators and enforce it then a whole lot of allocation techniques like memory pools couldn't be used with strcpy or would have to use char* type of strings again. The point is not that allocators don't know how much memory has been allocated, but that C has no idea about the underlying allocator, so it cannot ask it about the length of the string as it was proposed.
- admax88q 9y agoOkay but you don't have to implement a 100% solution to make 90% of existing code much safer. How much C code is out there that only uses malloc/free? All of those programs could be made safer if the default string methods were able to prevent writing past the end of the array.
- adrianN 9y agoClang offers a memory sanitizer that does a lot of extra checking. People don't ship their software with the sanitizer activated because the performance hit is nontrivial.
- xtrapolate 9y agoYou're free to do as you please here. You don't have to use malloc()/free(), just implement your own LIBRARY_Alloc()/LIBRARY_Free()/LIBRARY_GetMemorySizeBytes() :)