【问题标题】:How to assign Hex value to Heap Memory in C如何在 C 中将十六进制值分配给堆内存
【发布时间】: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


【解决方案1】:

你可以使用memmove():

if (debug)
{
    int filler = 0xDEADBEEF;

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

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

【讨论】:

  • 也称为memcpy()
  • 正是我想要的。谢谢@itsme86。你能说我没有经验吗?
  • -1,这是错误的, int 不能保证与 int 指针的大小相同。如果 int 指针的大小为 8,而 int 的大小为 4,则您正在访问非法内存。
  • @self。这不会导致段错误吗?我刚查了一下,int的大小是4,int指针的大小是8,所以你是对的。
  • @ngwilliams 这将导致未定义的行为,并且任何事情都可能发生(读作:可能)。即使它们相等,您也不应该使用该代码。
猜你喜欢
  • 2012-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-29
  • 2020-04-14
  • 1970-01-01
  • 2015-02-14
  • 2011-09-05
相关资源
最近更新 更多