Browse Source

malloc: add malloc_usable_size()

Waldemar Brodkorb 3 years ago
parent
commit
1bc015efdd
2 changed files with 16 additions and 0 deletions
  1. 2 0
      include/malloc.h
  2. 14 0
      libc/stdlib/malloc-standard/malloc_usable_size.c

+ 2 - 0
include/malloc.h

@@ -162,6 +162,8 @@ extern int malloc_trim(size_t pad);
 /* Prints brief summary statistics on the stderr. */
 extern void malloc_stats(void);
 
+extern size_t malloc_usable_size(void *);
+
 /* SVID2/XPG mallopt options */
 #ifndef M_MXFAST
 # define M_MXFAST  1	/* UNUSED in this malloc */

+ 14 - 0
libc/stdlib/malloc-standard/malloc_usable_size.c

@@ -0,0 +1,14 @@
+/*
+  malloc_usable_size - fully inspired by musl implementation
+*/
+
+#include "malloc.h"
+
+/* for malloc_usable_size  */
+#define OVERHEAD (2*sizeof(size_t))
+#define CHUNK_SIZE(c) ((c)->size & -2)
+#define MEM_TO_CHUNK(p) (struct malloc_chunk *)((char *)(p) - OVERHEAD)
+
+size_t malloc_usable_size(void *p) {
+	return p ? CHUNK_SIZE(MEM_TO_CHUNK(p)) - OVERHEAD : 0;
+}