Heap allocation of pointers in struct

Came across this piece of code in android's service_manaer.c and the heap allocation of the instance is interesting.

struct svcinfo
{
struct svcinfo *next;
void *ptr;
struct binder_death death;
unsigned len;
uint16_t name[0];
};

An instance of this struct is dynamically created,

struct svcinfo * si = malloc(sizeof(*si) + (len + 1) * sizeof(uint16_t));

This could have also been done by just allocating the memory for the pointer like name_ptr and having that point to another section of heap memory (holding the name). But the above approach has some advantages, first that memory for the pointer isn't needed explicitly and that the entire object would be allocated in a virtually contiguous memory and a higher possibility for the entire object to be present in a same page.

This could have also been done by just allocating the memory for the pointer like name_ptr and having that point to another section of heap memory (holding the name). But the above approach has some advantages, first that memory for the pointer isn't needed explicitly and that the entire object would be allocated in a virtually contiguous memory and a higher possibility for the entire object to be present in a same page.

No comments: