preface ：

1 If variable var To use 2 Of N Power alignment , with 16 byte Alignment as an example , We know 16=
0x10, that 16byte Aligned values must match bit0~3 All are 0 The law of , for example 32=0x20,48=0x30 etc. ;

Then given a random number , How to achieve bit0~3 All are 0 What's the effect ,var
&~0x0f that will do . Homology , If necessary 32byte alignment , First look 32byte What is the hexadecimal correspondence of ,32=0x20,bit0~bit4 Need all 0. achieve 32byte Alignment required var
&~0x1f Only then . It should be able to draw a more general conclusion by analogy , If variable var Need to align byte( by 2 Of N pow ) alignment , The current value can be var & ~(align
-1) Can achieve the goal .

2  Here's another question , How to achieve any byte alignment ? Assumed value 366, I just want him to become 199 Integral multiple of ,366 - 366%199 =
199 That's what it's all about . So I want him to become 199*2 =398 What about ,388+199 - 388%199 = 398 That's what it's all about .

3 cpu Accessible address , Generally, at least 4 byte alignment , So no 2 The possibilities mentioned in .

scene ：

be based on ANSI Of malloc/free realization align_malloc/align_free function , realization 2 Of N Power byte alignment , Hypothetical requirements 64byte alignment . The key to achieve this is to save base_addr, That's how it works free Drop allocated area , Prevent memory leaks . The test code is as follows ：

There is a special case , Is when base_ptr If it is already aligned , Will still base_ptr Add up align_bytes, Compatibility reached .
#include <stdio.h> #include <stdlib.h> void *align_ptr_malloc(int size,int
align_bytes) { void *base_ptr = NULL; void *mem_ptr = NULL; base_ptr =
malloc(size + align_bytes);//alloc alignbytes, rather than align_bytes-1,
because we need to store offset mem_ptr = (void *)((int)((int *)base_ptr +
align_bytes -1) & ~(align_bytes-1)); if(mem_ptr == base_ptr)//base_ptr already
align_bytes align { mem_ptr = base_ptr + align_bytes;//force move it to one
more alignbytes } *((int *)mem_ptr-1) = mem_ptr - base_ptr; printf("offset is
%d base prt %x mem_ptr %x\n",*((int *)mem_ptr -1),base_ptr,mem_ptr); return
mem_ptr; } void *align_ptr_free(void *ptr) { void *base_addr = NULL; printf("%x
%x\n",ptr,*((int *)ptr - 1)); base_addr = (void *)(ptr- *((int *)ptr-1));