我编写了一个程序,输入 3 个数字:
- 使用
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/