c - Storing control information alongside allocated memory. Is it portable? -
very briefly, trying write allocation routines (of type unsigned char) each allocated block has control information associated it. not trying write full fledged memory manager have specific requirement
a sample of our control structure
typedef struct _control_data { u8 is_segment; : : : struct _control_data* next; }control_data; when user calls alloc size 40, allocate
unsigned char* data_ptr = (unsigned char*)malloc(sizeof(control_data) + size); return(&data_ptr[sizeof(control_data]); later user pass pointer returned during alloc , want access control information.
void do_some_processing(unsigned char* data_ptr) { struct control_data* c_ptr = (data_ptr - sizeof(control_data)); c_ptr->is_segment = true; c_ptr->next = null; } is above access legal , portable?
yes, should fine , common technique.
a few points:
- don't cast return value of
malloc()in c. - use pointer arithmetic advantage:
void * my_alloc(size_t size) { control_data *cd = malloc(size + sizeof *cd); if(cd != null) return cd + 1; return null; } the + 1 right thing, way simpler. there's no point in making allocation "typed"; let return void * , leave caller use unsigned char * pointer store returned value.
update: pointed out in comment, ignores alignment (which feels safe since non-control data array of unsigned char) might problem in general case.
Comments
Post a Comment