Is alignment combining required for a memory allocation header?

In K & R2, they implement a memory allocator in chapter 8. For each block, there is a header defining something like this (the code may be inaccurate from memory):

union header_t
{
  struct 
  {
     unsigned size;
     unsigned* next; 
  };

  long align;
};

They do this to "make sure the title is correctly aligned with the long". But does the union unite the largest member? The structure is larger than a single alignment element, so the title will align to structural multiples anyway, no?

How about when the structure is even larger (they say that it has many members). Is this allied trick always needed when you write a memory allocator?

+3
source share
3 answers

" , ".

, ? , unsigned unsigned* 32 , long - 128 ( , 16 64 )?

-, ? , long, , , long. unsigned unsigned* , . , , long .

+1

K & R:

union header
{
  struct 
  {
     union header *ptr; 
     unsigned size;
  } s;

  Align x;
};

, :

union header_t
{
  struct 
  {
     union header_t *next; 
     unsigned size;
  } s;
};

(, struct, struct union header_t *, .)

K & R malloc() , , . malloc , , , .

, :

typedef union header Header;
static Header base;
Header *p = &base;
...
p += p->s.size;
return (void *)(p+1);

, p+1 (cast to void *), , . p Header *, , sizeof(Header) , (, p+1 sizeof(Header) bytes from p). , Header .

struct Header . , Header , union, , , , .. . K & R , long. , , Header Align. , Align - , , .

, " " , C , malloc, , . , long Align.

+4

The size of these data types is platform dependent. I assume that the two unsigned elements of the structure are 16 bits and the long alignment is 32 bits or two 32-bit elements in the structure and 64 bits for the long.

Alignment boundaries will be either 32 or 64 bits

0
source

Source: https://habr.com/ru/post/1725722/


All Articles