Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does malloc return NULL in a bare-metal environment?

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:

  • In a bare-metal environment, when does malloc return NULL?
  • In a bare-metal environment, how to prevent stack from overlapping with heap?
like image 830
lrouter Avatar asked Dec 24 '22 02:12

lrouter


2 Answers

@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).

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 :) .

like image 72
cxw Avatar answered Jan 04 '23 23:01

cxw


Size of stack is determinded at compile time.

      +--------+   Last Address of RAM
      | Stack  |
      |   |    |
      |   v    |
      +--------+
RAM   |        |
      +--------+   Stack Limit
      |        |
      +--------+
      |   ^    |
      |   |    |
      | Heap   |
      +--------+
      |   ZI   |
      +--------+
      |   RW   |  
      +========+  First Address of RAM

malloc return null if there is not enough space for the requested heap.

And its your duty to to prevent stack overflow!

like image 28
Wiki Wang Avatar answered Jan 04 '23 22:01

Wiki Wang