【发布时间】:2014-03-07 00:10:42
【问题描述】:
我正在尝试在 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;
}
感谢任何帮助或建议,谢谢!
【问题讨论】:
-
如果您确保从 mmap() 返回的地址正确对齐,那么您可以将 void 指针转换为 mmap() 返回的任何其他指针,如 int,然后使用简单循环设定你的价值观。我从规范中引用:指向 void 的指针可以转换为指向任何对象类型的指针或从指向任何对象类型的指针。 请注意,它必须转换为兼容的类型。
标签: c memory-management hex