如何在C中为堆内存分配十六进制值

如何在C中为堆内存分配十六进制值,c,memory-management,hex,C,Memory Management,Hex,我试图在C中创建一个内存分配器(基本上是使用mmap()重新创建malloc()),但部分规范是,如果调试标志处于启用状态,则需要根据需要,首先使用可识别的十六进制模式0xDEADBEEF填充分配的内存。我已经能够创建负责初始化内存块的代码,但我不知道如何有条理地将十六进制值分配给内存。我的代码如下: static void *base; struct free_header *head; int successfulInit = 0; int GlobalDe

我试图在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;
}
static void*base;
结构自由_头*头;
int successfulInit=0;
int GlobalDebug=0;
无结构头{
整数大小;
结构自由_头*下一步;
};
结构对象头{
整数大小;
智力测验;
};
int m_错误;
int Mem_Init(int sizeOfRegion,int debug){
如果(sizeOfRegion size=newSize;
head->next=NULL;
//关闭设备
关闭(fd);
//设置表示呼叫成功的标志
successfulInit=1;
返回0;
}

非常感谢您的帮助或建议,谢谢!

您可以使用
memmove()

if(调试)
{
int filler=0x0;
无效*ptr;
对于(ptr=startByte;ptr-startByte

如果大小不是sizeof(int*)的精确倍数,则只需在区域末尾的剩余字节中复制一部分填充符,但这只是一个开始。

也称为
memcpy()
。正是我想要的。谢谢@itsme86。你能告诉我我没有经验吗?-1,这是错误的,int不能保证与int指针大小相同。如果int指针大小为8,int指针大小为4,你正在访问非法内存。@self。这不会导致segfault吗?我刚刚检查了int,int指针大小为4,int指针大小为8,所以你是正确的。@ngwilliams它将导致未定义的行为,因此任何事情都可能发生(读作:可能)。即使它们相等,也不应该使用该代码。如果确保从mmap()返回的地址正确对齐,则可以强制转换空指针,而mmap()返回任何其他指针,如int,然后使用简单循环设置值。我引用规范:指向void的指针可以转换为指向任何对象类型的指针,也可以转换为指向任何对象类型的指针。请注意,它必须转换为兼容类型。
if (debug)
{
    int filler = 0xDEADBEEF;

    void *ptr;
    for (ptr = startByte; ptr - startByte < size; ptr += sizeof(int *))
        memmove(ptr, &filler, sizeof(int *));
}