Proposed addition of malloc_size_np()
Matthew Dillon
dillon at apollo.backplane.com
Sat Mar 25 08:06:35 UTC 2006
:
:=== Proposal ===
:Add malloc_size_np() to libc, and provide the prototype in malloc_np.h:
:
: size_t
: malloc_size_np(const void *ptr);
:
:This function would return the usable size of the allocation pointed to
:by ptr, which is always greater than or equal to the size that was
:specified in the call to malloc(), calloc(), posix_memalign(), or
:...
That creates a serious race condition for any threaded program,
since multiple threads might be malloc()ing memory at the same
time and one could wind up using the 'extra' space that abuts
an allocation being tested by some other thread.
Maybe something like:
n = realloc_try(ptr, bytes)
This function attempts to extend the size of a previously allocated
memory block without changing its pointer. The total size of the
(now possibly extended) memory pointed to by pointer is returned. The
total size returned will always be at least min(bytes, previous_size)
and will never exceed (bytes). The function cannot fail, but may not
return the requested number of bytes.
This function may also be used to truncate the size of a previously
allocated memory block without changing its pointer. This function
will always return (bytes) when the passed bytes is less then or
equal to the size of the current allocation. The function does NOT
guarentee that the memory allocator can actually use the freed memory
past the truncation point for other unrelated allocations, but it DOES
guarentee that, baring other allocations that reuse the memory, the
current allocation can be extended back into the truncated area with
another call to realloc_try().
--
That would give you the most flexibility and be relatively opaque to the
actual malloc implementation. The degenerate case would only have
to determine the size of the current allocation to return a meaningful
result (even if it doesn't actually extend or truncate it), and that
information clearly must already be attainable since the original
allocation size is not specified when you free() the memory.
-Matt
More information about the freebsd-arch
mailing list