简体   繁体   中英

Storing control information alongside allocated memory. Is it portable?

Very briefly, we are trying to write some allocation routines (of type unsigned char) where each allocated block has some control information associated with it. We are not trying to write a full fledged memory manager but have some specific requirement

A sample of our control structure

typedef struct _control_data
{
   u8 is_segment;
   :
   :
   :
   struct _control_data* next;
}control_data;

When the user calls alloc for size 40, we will allocate

  unsigned char* data_ptr = (unsigned char*)malloc(sizeof(control_data) + size);
  return(&data_ptr[sizeof(control_data]);

Later the user will pass the pointer returned during alloc and we want to access the 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 the above access legal and portable?

Yes, it should be fine and is a 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 will do exactly the right thing, but is way simpler. Also there's no point in making the allocation "typed"; let it return void * and leave it up to the caller to use an unsigned char * pointer to store the returned value.

UPDATE : As pointed out in a comment, this ignores alignment (which feels safe since you say the non-control data is an array of unsigned char ) which might be a problem in the general case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM