#include<sys/mman.h>
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
//作者使用的64位机器,sizeof(size_t)也就是sizeof(long)
void* malloc ( size_t size )
{
long* ptr = mmap( 0, size + sizeof(long), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0 );
if (ptr == MAP_FAILED) {
return NULL;
}
*ptr = size; // First 8 bytes contain length.
return (void*)(&ptr[1]); // Memory that is after length variable
}
void *calloc(size_t n, size_t size) {
void* ptr = malloc(n * size);
if (ptr == NULL) {
return NULL;
}
memset(ptr, 0, n * size);
return ptr;
}
void *realloc(void *ptr, size_t size)
{
if (size == 0) {
free(ptr);
return NULL;
}
if (ptr == NULL) {
return malloc(size);
}
long *plen = (long*)ptr;
plen--; // Reach top of memory
long len = *plen;
if (size <= len) {
return ptr;
}
void* rptr = malloc(size);
if (rptr == NULL) {
free(ptr);
return NULL;
}
rptr = memcpy(rptr, ptr, len);
free(ptr);
return rptr;
}
void free (void* ptr )
{
if (ptr == NULL) {
return;
}
long *plen = (long*)ptr;
plen--; // Reach top of memory
long len = *plen; // Read length
munmap((void*)plen, len + sizeof(long));
}