c - Allocate Pointer and pointee at once -


if want reduce malloc()s (espacially if data small , allocated often) allocate pointer , pointee @ once.

if assume following:

struct entry {     size_t      buf_len;     char        *buf;     int         something; }; 

i allocate memory in following way (don't care error checking here):

size_t buf_len  = 4;                // size of buffer struct entry *e = null;  e = malloc( sizeof(*e) + buf_len ); // allocate struct , buffer e->buf_len  = buf_len;              // set buffer size e->buf      = e + 1;       // buffer lies behind struct 

this extende, whole array allocated @ once.

how assess such technuique regard to:

  • portability
  • maintainability / extendability
  • performance
  • readability

is reasonable? if ok use, there ideas on how design possible interface that?

you use flexible array member instead of pointer:

struct entry {     size_t      buf_len;     int         something;     char        buf[]; };  // ... struct entry *e = malloc(sizeof *e  + buf_len); e->buf_len = buf_len; 

portability , performance fine. readability: not perfect enough.

extendability: can't use more 1 member @ time, you'd have fall explicit pointer version. also, explicit pointer version means have muck around ensure correct alignment if use type doesn't have alignment of 1.

if thinking i'd consider revisiting entire data structure's design see if there way of doing it. (maybe way best way, have think first).


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

gradle error "Cannot convert the provided notation to a File or URI" -

python - NameError: name 'subprocess' is not defined -