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:

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

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

c++ - Correct method for redrawing a layered window -

java.util.scanner - How to read and add only numbers to array from a text file -