Search code examples
callocation

Allocate Pointer and pointee at once


If I want to reduce malloc()s (espacially if the data is small and allocated often) I would like to allocate the pointer and pointee at once.

If you assume something like the following:

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

I would like to allocate memory in the following way (don't care about error checking here):

size_t buf_len  = 4;                // size of the buffer
struct entry *e = NULL;

e = malloc( sizeof(*e) + buf_len ); // allocate struct and buffer
e->buf_len  = buf_len;              // set buffer size
e->buf      = e + 1;       // the buffer lies behind the struct

This could even be extende, so that a whole array is allocated at once.

How would you assess such a technuique with regard to:

  • Portability
  • Maintainability / Extendability
  • Performance
  • Readability

Is this reasonable? If it is ok to use, are there any ideas on how to design a possible interface for that?


Solution

  • You could use a flexible array member instead of a 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 and performance are fine. Readability: not perfect but good enough.

    Extendability: you can't use this for more than one member at a time, you'd have to fall back to your explicit pointer version. Also, the explicit pointer version means that you have to muck around to ensure correct alignment if you use it with a type that doesn't have an alignment of 1.

    If you are seriously thinking about this I'd consider revisiting your entire data structure's design to see if there is another way of doing it. (Maybe this way is actually the best way, but have a good think about it first).