Skip to main content
Angelo1
Associate III
March 30, 2014
Question

stm32f405 malloc issue

  • March 30, 2014
  • 13 replies
  • 2717 views
Posted on March 31, 2014 at 01:11

Dear,

as in several examples, i implemented my _sbrk function to be able to use malloc, as (copied from examples):

extern int  _end;

/*

 * _sbrk needed for malloc

 */

caddr_t _sbrk ( int incr ) {

        static unsigned char *heap = NULL;

        unsigned char *prev_heap;

        if (heap == NULL) {

                heap = (unsigned char *)&_end;

        }

        prev_heap = heap;

        /* check removed to show basic approach */

        heap += incr;

        return (caddr_t) prev_heap;

}

Program compiles fine, no warnings, if i call directly _sbrk to allocate memory (instead of malloc) it works perfect, if i instead call ''malloc'', i see that _sbrk is called, but the return value of malloc is an null pointer (0).

Probably, malloc after calling sbrk do some other checks, and returns 0.

Every help is appreciated.

Thanks

#worst-forum-software-ever
    This topic has been closed for replies.

    13 replies

    stm322399
    Senior
    March 31, 2014
    Posted on March 31, 2014 at 13:59

    Angelo,

    I implemented the most trivial _sbrk as possible, and malloc magically worked out-of-the-box without headaches. However it came to my mind that you may miss one of these:

    - calling __libc_init_array as early as possible

    - make sure to zero bss area from __bss_start__ to __bss_end__.

    Hope, it can help.

    Angelo1
    Angelo1Author
    Associate III
    March 31, 2014
    Posted on March 31, 2014 at 15:13

    Dear Gonzalez and all,

    first a big thank for the kind support from all. This is not trivial, seems on many forums newby gets often brutal answers.

    I realized from your answers above that since i choosed to avoid an OS (-nostartfiles, etc) maybe it has not sense now try to enabling malloc. Actually it simply cannot work.

    I have -nostartfiles, and i also have -Wl,--gc-sections enabled, and a quite minimal startup.s so to modify all for malloc to work i probably have to go through several things.

    My idea is to go for static allocation that seems to be enough for my app.

    Best Regards,

    Angelo

    chen
    Associate II
    March 31, 2014
    Posted on March 31, 2014 at 15:57

    Hi

    ''I realized from your answers above that since i choosed to avoid an OS (-nostartfiles, etc) maybe it has not sense now try to enabling malloc. Actually it simply cannot work.''

    The main problem is that you are trying to get malloc() working without an OS. The implementation of malloc() from gnu assumes that there will be some kind of infrastructure from a OS.

    You could try a version of malloc() from an embedded system. Have a look a the malloc() implementations from FreeRTOS (there are 4, one of them is simply calling the gnu one).