我正在尝试用 C 创建一个内存分配器(基本上是使用 mmap() 重新创建 malloc()),但规范的一部分是,如果调试标志打开,我需要首先用可识别的内存填充分配的内存十六进制模式 0xDEADBEEF,根据需要。我已经能够创建负责初始化内存块的代码,但我不知道如何有条理地将十六进制值分配给内存。我的代码如下:
static void *base;
struct free_header *head;
int successfulInit = 0;
int GlobalDebug = 0;
struct free_header {
int size;
struct free_header *next;
};
struct object_header {
int size;
int test;
};
int m_error;
int Mem_Init(int sizeOfRegion, int debug) {
if (sizeOfRegion <= 0) {
m_error = E_BAD_ARGS;
return -1;
} else if (successfulInit == 1) {
m_error = E_BAD_ARGS;
return -1;
}
GlobalDebug = debug;
// open the /dev/zero device
int fd = open("/dev/zero", O_RDWR);
// need to see if its divisible and returns a whole number
int pageSize = getpagesize();
int newSize = sizeOfRegion;
if((sizeOfRegion%pageSize) != 0){
int addTo = pageSize - (sizeOfRegion % pageSize);
newSize += addTo;
}
// size (in bytes) needs to be evenly divisble by the page size
base = mmap(NULL, newSize, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
if (base == MAP_FAILED || base == NULL) {
m_error = E_BAD_ARGS;
return -1;
}
head = base;
head->size = newSize;
head->next = NULL;
// close the device
close(fd);
// set flag saying the call was successful
successfulInit = 1;
return 0;
}
感谢任何帮助或建议,谢谢!
最佳答案
你可以只使用memmove()
:
if (debug)
{
int filler = 0xDEADBEEF;
void *ptr;
for (ptr = startByte; ptr - startByte < size; ptr += sizeof(int *))
memmove(ptr, &filler, sizeof(int *));
}
如果大小不是 sizeof(int *) 的精确倍数,则必须仅复制该区域末尾剩余字节中的部分填充符,但这只是一个开始。
关于c - 如何在C中将十六进制值分配给堆内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22238909/