malloc - Associating metadata in custom memory allocator for C89/C90 -
let's have following implementation custom memory allocator wrapping standard malloc
, free
library functions:
#include <stdlib.h> #include <stddef.h> struct metadata { void *private; size_t len; char data[1]; }; void *custom_malloc(size_t len) { struct metadata *mtdata; mtdata = malloc(offsetof(struct metadata, data) + len); if (mtdata == null) return null; mtdata->private = null; /* or pointer implementation data */ mtdata->len = len; return mtdata->data; } void custom_free(void *ptr) { struct metadata *mtdata; char *bytes; bytes = ptr; mtdata = (struct metadata *)(bytes - offsetof(struct metadata, data)); /* stuff mtdata->private , mtdata->len */ free(mtdata); }
is implementation valid (for c89/c90)?
ultimately, goal allocate contiguous memory len
bytes requested user, associate them metadata. since not know length @ compile-time, data
member declared array of char
, which, understanding, can used alias object.
i unsure alignment issues because while pointer returned malloc
guaranteed satisfy alignment requirements of pointers object type, data
member of struct metadata
might not after adding offsetof
.
if not valid, there way achieve want (that is, associating metadata allocated memory, can accessed in custom_free
function through pointer)?
i don't mind if metadata located contiguously before or after user data, nor in separate location (such obtained separate call malloc
). need able access somehow through ptr
user data passed custom_free
.
Comments
Post a Comment