I\'m currently working on an embedded project (STM32F103RB, CooCox CoIDE v.1.7.6 with arm-none-eabi-gcc 4.8 2013q4) and I\'m trying to understand how malloc() b
Here you can find how I could "force" malloc() to return NULL, if the heap is too small for allocating based on berendi's previous answer. I estimated the maximum amount of STACK and based on this I could calculate the address where the stack can start in worst case.
#define STACK_END_ADDRESS 0x20020000
#define STACK_MAX_SIZE 0x0400
#define STACK_START_ADDRESS (STACK_END_ADDRESS - STACK_MAX_SIZE)
void * _sbrk_r(
struct _reent *_s_r,
ptrdiff_t nbytes)
{
char *base; /* errno should be set to ENOMEM on error */
if (!heap_ptr) { /* Initialize if first time through. */
heap_ptr = end;
}
base = heap_ptr; /* Point to end of heap. */
#ifndef STACK_START_ADDRESS
heap_ptr += nbytes; /* Increase heap. */
return base; /* Return pointer to start of new heap area. */
#else
/* End of heap mustn't exceed beginning of stack! */
if (heap_ptr <= (char *) (STACK_START_ADDRESS - nbytes) ) {
heap_ptr += nbytes; /* Increase heap. */
return base; /* Return pointer to start of new heap area. */
} else {
return (void *) -1; /* Return -1 means that memory run out */
}
#endif // STACK_START_ADDRESS
}