malloc 什么时候在裸机环境中返回 NULL? [英] When does malloc return NULL in a bare-metal environment?
问题描述
有一个c内存模型如下:
There is a c memory model as following :
+--------+ Last Address of RAM
| Stack |
| | |
| v |
+--------+
RAM | |
| |
+--------+
| ^ |
| | |
| Heap |
+--------+
| ZI |
+--------+
| RW |
+========+ First Address of RAM
堆栈和堆空间以相反的方向增加.它们将在中间相互重叠.所以我的问题是:
The stack and heap space increase in opposite directions. They would be overlapped with each other in the middle. So my questions are:
- 在裸机环境中,malloc 什么时候返回 NULL?
- 在裸机环境下,如何防止栈与堆重叠?
推荐答案
@WikiWang 是正确的,如果您使用的是静态的编译时内存布局(edit 尽管您必须告诉您的 malloc
以某种方式实现堆的末尾).
@WikiWang is correct if you are using a static, compile-time memory layout (edit although you have to tell your malloc
implementation somehow where the end of the heap is).
如果不是,并且假设您是指裸机,这取决于您的板支持包中的 C 库实现.该库必须提供 brk(2)
或具有类似效果的功能.malloc
在 brk
或 sbrk
设置的内存区域内工作.例如,参见 malloc 源码调用宏 MORECORE
,默认为 sbrk
.您的 C 库将不得不使用内核调用以外的其他东西:).
If not, and assuming you mean bare-metal, it depends on the C library implementation in your board-support package. The library must provide some implementation of brk(2)
or a function having a similar effect. malloc
works within the area of memory set by brk
or sbrk
. For example, see the malloc source calling macro MORECORE
, which is by default sbrk
. Your C library will have to use something other than a kernel call for that :) .
这篇关于malloc 什么时候在裸机环境中返回 NULL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!