c - 如何在C中将十六进制值分配给堆内存

标签 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;
}

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

最佳答案

你可以只使用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/

相关文章:

c# - 将十六进制字符串解析为以 10 为基数的长整数

c - 将十六进制命令传递给 c 函数

c - 有什么与\n 相反的东西可以让我回到上一行吗?

swift - deinitialize() 与 deallocate()

更改函数中传递的指针

c - n维(n>=2)数组在内存中是如何表示的?

iphone - 惯用的短生命周期本地对象类似于 RAII

unix - 如何在 Unix 中打印十六进制值 255?

c - c代码汇编输出中的if语句

c - 使用哪个 IP 使用 telnet C 连接到两台不同的计算机