不玩游戏的时候能不能把独立显卡给关了?# Hardware - 计算机硬件
P*c
1 楼
16.9 Write an aligned malloc & free function that takes number of bytes and
aligned byte (which is always power of 2)
Example
align_malloc(1000, 128) will return a memory address that is a multiple of
128 and that points to memory of size 1000 bytes.
aligned_free() will free memory allocated by align_malloc.
答案:
void* aligned_malloc(size_t required bytes, size_t alignment){
void* p1; //original block
void** p2; //aligned block
int offset = alignment-1+sizeof(void*);
if ((p1 = (void*)malloc(required_bytes+offset))==NULL) {
return NULL;
}
p2=(void**) (((size_t)(p1)+offset) & ~(alignment-1));
p2[-1]=p1;
return p2;
}
void aligned_free(void* p){
free(((void**)p)[-1];
}
感觉书上讲的不是很清楚。有人能详细讲一下那个offset怎么算出来的吗。还有任何数
& ~(alignment-1) 之后都是alignment的倍数了吧。p2是定义成void**, 返回的时候
变成void*, free的时候又被cast成void**, 用意是什么。
aligned byte (which is always power of 2)
Example
align_malloc(1000, 128) will return a memory address that is a multiple of
128 and that points to memory of size 1000 bytes.
aligned_free() will free memory allocated by align_malloc.
答案:
void* aligned_malloc(size_t required bytes, size_t alignment){
void* p1; //original block
void** p2; //aligned block
int offset = alignment-1+sizeof(void*);
if ((p1 = (void*)malloc(required_bytes+offset))==NULL) {
return NULL;
}
p2=(void**) (((size_t)(p1)+offset) & ~(alignment-1));
p2[-1]=p1;
return p2;
}
void aligned_free(void* p){
free(((void**)p)[-1];
}
感觉书上讲的不是很清楚。有人能详细讲一下那个offset怎么算出来的吗。还有任何数
& ~(alignment-1) 之后都是alignment的倍数了吧。p2是定义成void**, 返回的时候
变成void*, free的时候又被cast成void**, 用意是什么。