我正在尝试制作内存管理的一个端口,其中一些分配器使用虚拟内存机制来保留地址空间,而不(在开始时)分配任何物理内存,然后仅在需要时分配内存。
该代码基于Windows的VirtualAlloc和VirtualFree来使事情正常工作,现在我正在尝试将此代码移植到Apple OS X,据我所知,没有这样的API,过了一会儿我出现了使用以下代码:
//to reserve virtual address space
//equivalent of VirtualAlloc(NULL, size, MEM_RESERVE, PAGE_NOACCESS)
void* ptr = mmap(NULL, size, PROT_NONE, (MAP_PRIVATE | MAP_ANON), -1, 0);
msync(ptr, size, (MS_SYNC | MS_INVALIDATE));
//to free ALL virtual address space
//equivalent of VirtualFree(addr, 0, MEM_RELEASE)
//where "size" is the size of the entire virtual address space and "addr" the starting address
msync(addr, size, MS_SYNC);
munmap(addr, size);
//to allocate physical memory
//equivalent of VirtualAlloc(addr, size, MEM_COMMIT, PAGE_READWRITE)
void* ptr = mmap(addr, size, (PROT_READ | …Run Code Online (Sandbox Code Playgroud)