I am writing an embedded software for STM32F7 and my libc is newlib-2.4.0.20160527.
I have implemented _sbrk()
as follows:
extern intptr_t g_bss_end; /* value after the last byte in .bss */
extern intptr_t g_msp_lim; /* stack buffer starts at this address */
intptr_t _sbrk(ptrdiff_t heap_incr)
{
static intptr_t heap_end = 0;
intptr_t prev_heap_end;
intptr_t new_heap_end;
if(heap_end == 0) {
heap_end = (intptr_t)&g_bss_end;
}
prev_heap_end = heap_end;
new_heap_end = prev_heap_end + heap_incr;
if(new_heap_end >= g_msp_lim) {
errno = ENOMEM;
return -1;
}
heap_end = new_heap_end;
return prev_heap_end;
}
Then, when I do the following:
/* total capacity of my heap is 0x40000 */
void * mem = malloc(0x40000);
free(mem); mem = 0;
mem = malloc(0x40000);
everything works fine (i.e., malloc returns non-zero twice).
But when I do the following (for testing purposes):
for(int32_t sz = 0x50000; sz >= 0; sz--) {
void * mem = malloc(sz);
if(mem != 0) {
__BKPT();
free(mem);
break;
}
}
every malloc()
fails, even malloc(0)
(i.e., __BKPT()
is never reached). So, there is no allocated memory on heap in fact (I did not get any mem != 0
so I can not even free()
something) and there is also no available memory.
I expected malloc()
to fail for every sz > 0x40000
and succeed for every sz <= 0x40000
(assuming free()
works fine after each malloc()
).
Have I missed something, or this is either a bug or intended behavior in newlib?
malloc
in embedded systems is most often a bad idea and disallowed by many coding standards for good reasons. Notably deterministic behaviour and guaranteed allocation. Evaluate the use of pools or other measures like static variables before even thinking aboutmalloc
etc!NULL
macro with pointers.0
as null pointer constant is valid, but a bad habit from C++ programmers. C++11 introducednullptr
for good reasons. (Wish C11 had followed them)mem
;__BKPT()
was also a breakpoint). To get inside the newlib's code with gdb I am recompiling it with-g3 -O0
now. I want to have workingsnprintf
which relies onmalloc
. Should I start searchingsnprintf
alternatives? I do not needmalloc
for anything else.snprintf
would requiremalloc
.0
is null pointer constant in C. It isn't a "bad habit from C++", it has been used that way since well before C++ was invented