现在我在看C的接口和实现。图四是内存管理。它说alighment保证了任何类型的数据都可以存储在Mem_alloc函数返回的块中。我怎么理解这句话?有必要吗?管理内存时对齐?
对齐代码如下:
union align {
#ifdef MAXALIGN
char pad[MAXALIGN];
#else
int i;
long l;
long *lp;
void *p;
void (*fp)(void);
float f;
double d;
long double ld;
#endif
void *Mem_alloc(long nbytes, const char *file, int line){
struct descriptor *bp;
void *ptr;
assert(nbytes > 0);
nbytes = ((nbytes + sizeof (union align) - 1)/
(sizeof (union align)))*(sizeof (union align));
for (bp = freelist.free; bp; bp = bp->free) {
if (bp->size > nbytes) {
bp->size -= nbytes;
ptr = (char *)bp->ptr + bp->size;
if ((bp = dalloc(ptr, nbytes, file, line)) != NULL) {
unsigned h = hash(ptr, htab);
bp->link = htab[h];
htab[h] = bp;
return ptr;
} else
{
if (file == NULL)
RAISE(Mem_Failed);
else
Except_raise(&Mem_Failed, file, line);
}
}
if (bp == &freelist) {
struct descriptor *newptr;
if ((ptr = malloc(nbytes + NALLOC)) == NULL
|| (newptr = dalloc(ptr, nbytes + NALLOC,
__FILE__, __LINE__)) == NULL)
{
if (file == NULL)
RAISE(Mem_Failed);
else
Except_raise(&Mem_Failed, file, line);
}
newptr->free = freelist.free;
freelist.free = newptr;
}
}
assert(0);
return NULL;
}
};
void *Mem_resize(void *ptr, long nbytes,
const char *file, int line) {
struct descriptor *bp;
void *newptr;
assert(ptr);
assert(nbytes > 0);
if (((unsigned long)ptr)%(sizeof (union align)) != 0
|| (bp = find(ptr)) == NULL || bp->free)
Except_raise(&Assert_Failed, file, line);
newptr = Mem_alloc(nbytes, file, line);
memcpy(newptr, ptr,
nbytes < bp->size ? nbytes : bp->size);
Mem_free(ptr, file, line);
return newptr;
}
我如何理解这些代码?为什么在调整空间大小时需要 if (((unsigned long)ptr)%(sizeof (union align)) != 0 ?