gpt4 book ai didi

kernel - __get_free_pages 的奇怪返回类型

转载 作者:行者123 更新时间:2023-12-04 02:21:31 25 4
gpt4 key购买 nike

为什么返回 unsigned long?为什么不是 void* 或 char*?

unsigned long __get_free_pages(unsigned int gfp_mask, unsigned int order)

我猜它会返回一个地址,还是我完全误解了该函数?

最佳答案

你更正了,它返回分配的第一页的第一个字节的内存地址。有趣的是 __get_free_pages() 内部使用的 page_address() 实际上返回 void*

这样做的原因可以在 LDD3, chapter 11 (PDF) 中找到:

Although you must be careful when mixing different data types, sometimes there are good reasons to do so. One such situation is for memory addresses, which are special as far as the kernel is concerned. Although, conceptually, addresses are pointers, memory administration is often better accomplished by using an unsigned integer type; the kernel treats physical memory like a huge array, and a memory address is just an index into the array. Furthermore, a pointer is easily dereferenced; when dealing directly with memory addresses, you almost never want to dereference them in this manner. Using an integer type prevents this dereferencing, thus avoiding bugs. Therefore, generic memory addresses in the kernel are usually unsigned long, exploiting the fact that pointers and long integers are always the same size, at least on all the platforms currently supported by Linux.

关于kernel - __get_free_pages 的奇怪返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28710083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com