c - 使用 malloc 探索堆内存

标签 c malloc heap-memory

我编写了一个程序,输入 3 个数字:

    1. 使用 malloc() 在堆中分配的内存大小
  • 两个 int

如果q是一个unsigned char指针,它会从q[min]给出q[i]=b > 到 q[max]

我认为堆被划分为页面,并且第一次调用 malloc() 会给出一个指向我的进程页面的第一个字节的指针。那么为什么如果尝试获取 q[-1] 我的进程没有被终止呢?

然后我尝试使用另一个指针p,我注意到两个指针之间有32byte的距离,为什么它们不相邻?

我注意到的最后一件事是,在 p[-8]=q[-40(-32-8)]q[-8] 中是数字33 00100001(所有其他字节都设置为0),它意味着什么?

谢谢!

最佳答案

I thought that the heap was divided in pages and that the first call to malloc would have given a pointer to the first byte of the page of my process. So why if try to get q[-1] my process is not killed?

很可能是因为您的 malloc 实现在那里存储了一些东西。可能是 block 的大小。

Then I've tried with another pointer p and I noticed that between the two pointers there is a distance of 32byte, why they are not adjacents?

同样的原因。您的实现可能会将 block 的大小存储在它返回的地址之前的 block 中。

The last thing I notice is that both in p[-8]=q[-40(-32-8)] and q[-8] there is the number 33 (00100001), it means anything?

这可能对您的 malloc 实现有意义。但如果不查看实现,您就无法真正分辨出什么。

关于c - 使用 malloc 探索堆内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38443620/

相关文章:

c - Gets(string#) 函数跳过先获取请求

c - 在函数中将 volatile 变量作为常量参数传递

c - 堆内存分配

c - 存储一系列大小未知的值的最有效方法是什么?

Android Gradle 无法为对象堆保留足够的空间

c - 在 C11 匿名结构定义中使用宏

c - DevCPP 的库窗口

c - 为什么我要 free() 一个由 malloc() 分配的对象?

1490086 字节的 Android 错误 : I/dalvikvm-heap: Grow heap (frag case) to 16. 159MB

c++ - 合成析构函数是否会破坏堆上分配的内存?