c - 通过 malloc 故意隐藏内存

标签 c pointers malloc

所以我正在研究一个小的内存分配包,我想要指针的初始化来保存分配空间的大小以及它是通过我的一个函数分配的指示器(这是内存中大小之前的字符“q”)。因此,我尝试执行以下操作:

int qmem_alloc(unsigned num_bytes, void ** rslt){
  *rslt = malloc(num_bytes+sizeof(int)+sizeof(char));
  *((int*)rslt) = num_bytes;
  *(char*)(rslt+sizeof(int)) = 'q';
  rslt = rslt+sizeof(int) + sizeof(char);
  if(*rslt == NULL)
    return -1;
  else if(errno != 0){
    //Catch the rest of the errors
    return -2;
  }
  return 0;
}

但是,在我的main函数中,好像rslt地址前的内存传回后没有包含它应该包含的内容。我在这里通过更改指针地址做坏事吗?

最佳答案

您在某些地方缺少一定程度的间接访问。在取消引用之前使用 rslt 的任何地方都应该使用 *rslt:

int qmem_alloc(unsigned num_bytes, void ** rslt){
  *rslt = malloc(num_bytes+sizeof(int)+sizeof(char));
  if(*rslt == NULL)
    return -1;

  *((int*)*rslt) = num_bytes;
  *(char*)(*rslt+sizeof(int)) = 'q';
  *rslt = *rslt+sizeof(int) + sizeof(char);
  if(errno != 0){
    //Catch the rest of the errors
    return -2;
  }
  return 0;
}

此外,malloc 返回的内存已正确对齐以供任何使用。因为您返回 sizeof(int)+sizeof(char) == 5 个字节(假设一个 4 字节 int),这意味着您返回的指针可能不是。您需要至少再添加 3 个字节以将返回的缓冲区放在 8 字节的边界上。

关于c - 通过 malloc 故意隐藏内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52671052/

相关文章:

c - 如何在后台XCreateWindow?

c - 如何为 mmap 选择固定地址?

c - 段错误,数组打印C

c - C 中的字符串,&str

c - 为什么我的程序返回(空)和乱码而不是预期的输出

c - 多线程 C 应用程序应如何处理失败的 malloc()?

c - 为结构体数组分配内存

c - 返回指向已分配内存的指针?

C++:类问题

c - 编写一个排序函数对指向结构的指针数组进行排序