c - 在自定义 malloc 中附加调试 header

标签 c pointers malloc void-pointers pointer-arithmetic

我对我的 C 仍然很生锈,我只是没有弄清楚这一点。我想做的是实现我自己的 malloc,这样我就可以跟踪分配并调试对 free() 的缺失调用。我有一个这样的标题:

typedef struct MemoryInfo {
  mem_Kind kind;
  unsigned int id;
  struct MemoryInfo* prev;
  struct MemoryInfo* next;
} MemoryInfo;

我的自定义 malloc 看起来像这样:

void* my_malloc(mem_Kind kind, unsigned int size) {
  MemoryInfo* mem;

  allocCount++;
  mem = (MemoryInfo*)malloc(sizeof(MemoryInfo) + size);
  mem->id = id;
  mem->kind = kind;
  // set prev/next...

  return mem + sizeof(MemoryInfo); // return pointer to memory after header
}

但是我的指针算法显然是错误的,因为它很快就会爆炸得非常可怕。但是,如果我将 void* memory 添加到我的结构的末尾并执行另一个 malloc 那么它似乎做得很好,问题是我无法真正找到 中的 header my_free 如果我这样做。我基本上是在尝试添加 header ,这样我就可以做一些反向指针运算来免费获取 header 。

void my_free(void* memory) {
  MemoryInfo* mem = memory - sizeof(MemoryInfo); // not correct either
  allocCount--;
  free(mem);
}

我在这里做错了什么?

最佳答案

我认为您在添加到指针时遇到了问题。它必须是这样的:

return (char*)mem + sizeof(MemoryInfo); // return pointer to memory after header

void my_free(void* memory) {
  MemoryInfo* mem = (MemoryInfo*)((char*)memory - sizeof(MemoryInfo)); // not correct either
  allocCount--;
  free(mem);
}

顺便说一下。看看这个程序。

#include <stdio.h>

typedef struct MemoryInfo {
  int kind;
  unsigned int id;
  struct MemoryInfo* prev;
  struct MemoryInfo* next;
} MemoryInfo;



int main()
{
  MemoryInfo* ptr = 0;

  printf("sizeof: %d\n",sizeof(MemoryInfo));
  printf("%d\n",ptr+3);
  return 0;
}

我在指向 MemoryInfo 的指针上加了 3,但它的值变成了 3*sizeof(MemoryInfo)。

关于c - 在自定义 malloc 中附加调试 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10565516/

相关文章:

c++ - 在 C++ 中使用 C 头文件中的外部变量

c - c中的unsigned int是什么?

c - 将节点添加到链表末尾的函数签名有问题

c++ - c++中的malloc错误

c - 具有递归功能的 10 基的基数转换器 - C

c - 为什么 myFunction 和 myFunction 导入自定义函数的地址不同?

c++ - 在 C 中从 Rust 读取指针

linux - 为什么我执行的 sbrk 系统调用不起作用?

c++ - 从持有对象指针的列表中删除

崩溃代码(指针 C99)