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

时间:2014-03-07 00:10:43

标签: c memory-management hex

我正在尝试在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;
}

感谢任何帮助或建议,谢谢!

1 个答案:

答案 0 :(得分:2)

您可以使用memmove()

if (debug)
{
    int filler = 0xDEADBEEF;

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

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