When does malloc return NULL in a headless environment?

There is a memory model c as follows:

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

The stack and space of the heap grow in opposite directions. They will overlap with each other in the middle. So my questions are:

  • In a painless environment, when does malloc return NULL?
  • In an unsafe environment, how to prevent the stack from matching with the heap?
+4
source share
5 answers

@WikiWang is correct if you use a static compile-time memory layout ( change , although you need to say something about the implementation mallocsomewhere where the end of the heap is).

, , bare-metal, C . brk(2) , . malloc , brk sbrk. , . malloc, MORECORE, sbrk. C -, :).

+3

.

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

malloc null, .

!

+2

malloc NULL?

C. , malloc sbrk, Linux. Linux MCU, sbrk :

// Global variables.
extern unsigned int _heap;
extern unsigned int _eheap;
static caddr_t heap = NULL;

caddr_t _sbrk(int incr)
{
  caddr_t prevHeap;
  caddr_t nextHeap;

  if (heap == NULL) { // first allocation
    heap = (caddr_t) & _heap;
  }

  prevHeap = heap;

  // Always return data aligned on a 8 byte boundary
  nextHeap = (caddr_t) (((unsigned int) (heap + incr) + 7) & ~7);
  if (nextHeap >= (caddr_t) & _eheap) {
    errno = ENOMEM;
    return ((void*)-1); // error - no more memory
  } else {
    heap = nextHeap;
    return (caddr_t) prevHeap;
  }
}

_eheap script:

PROVIDE ( _eheap = ALIGN(ORIGIN(ram) + LENGTH(ram) - 8 ,8) );

malloc , . , , malloc.

?

sbrk, , malloc .

+2

1) , , , malloc

2) , , , .

3) - (windows, linux ..) , , -, , , , , , .

, , , . , , , . , , , , , , . , .

, / , , , . , , , , , , , , .

Bare metal , .

+2

malloc NULL, . - . , , ( ).

, . , . , malloc sbrk ( ), sbrk, . .

( ) . -, , , , . , ( , - , , ). MCU (MPU), , MPU. ( , ). ( ). , .

, , , , . malloc, , , . , .

+1

Source: https://habr.com/ru/post/1652263/


All Articles