-
20-09-2019 - |
문제
C (예 : 캐시 라인 경계)의 특정 경계에 정렬 된 메모리를 어떻게 할당합니까? 나는 최소한 32 ~ 64 비트 아키텍처 사이에서 가능한 한 휴대용이 될 수있는 Malloc/Free 구현을 찾고 있습니다.
추가로 편집 : 다시 말해서, 나는 (지금은 쓸모 없는가?)와 같은 행동을 찾고 있습니다. Memalign 함수, 무료를 사용하여 해제 할 수 있습니다.
해결책
다음은 Malloc으로의 호출을 캡슐화하고 정렬 목적을 위해 더 큰 버퍼를 할당하며, 나중에 호출을 위해 정렬 된 버퍼 직전에 원래 할당 된 주소를 저장하는 솔루션이 있습니다.
// cache line
#define ALIGN 64
void *aligned_malloc(int size) {
void *mem = malloc(size+ALIGN+sizeof(void*));
void **ptr = (void**)((uintptr_t)(mem+ALIGN+sizeof(void*)) & ~(ALIGN-1));
ptr[-1] = mem;
return ptr;
}
void aligned_free(void *ptr) {
free(((void**)ptr)[-1]);
}
다른 팁
사용 posix_memalign
/free
.
int posix_memalign(void **memptr, size_t alignment, size_t size);
void* ptr;
int rc = posix_memalign(&ptr, alignment, size);
...
free(ptr)
posix_memalign
표준 대체입니다 memalign
당신이 언급했듯이, 그것은 쓸모 없다.
어떤 컴파일러를 사용하고 있습니까? MSVC에 있다면 시도해 볼 수 있습니다 _aligned_malloc()
그리고 _aligned_free()
.
제휴하지 않습니다 StackOverflow