Heap not work

Share code examples or discuss embedded software, including device drivers, interrupt handlers, middleware and application code.

Moderators: Markus Girdland, Mattias Norlander

ArtemGromak
Posts: 5
Joined: Thu Mar 02, 2017 3:04 pm

Heap not work

Postby ArtemGromak » Mon Jan 28, 2019 3:28 pm

Hi.
I want to use dynamic memory allocation in my program. I generated the project in CubeMX (stm32H743), set the heap size to several kilobytes, but when I try to allocate memory, malloc always returns NULL, although there is enough memory. It turns out that CubeMx can not create the right project for TrueStudio. How can I solve the problem?
Thank.

ArtemGromak
Posts: 5
Joined: Thu Mar 02, 2017 3:04 pm

Re: Heap not work

Postby ArtemGromak » Thu Jan 31, 2019 11:08 am

An error occurs on these lines of code in the sbrc function.

Code: Select all

   if (heap_end + incr > min_stack_ptr)
   {
      errno = ENOMEM;
      return (caddr_t) -1;
   }

Then comment them out then memory is allocated.
Why it happens? Maybe something is wrong in the linker script?

antm
Posts: 5
Joined: Mon Mar 11, 2019 10:35 am

Re: Heap not work

Postby antm » Tue Mar 12, 2019 11:16 am

I'd suggest looking in the linker file for something like this:

_Min_Heap_Size = 0x200; /* required amount of heap */

sbrk will need to know where the end of the heap is, so you will need a variable defined correctly.

I don't use the standard dynamic memory allocation myself, so the function below is just from an example project I found (syscalls.c):

register char * stack_ptr asm("sp");

caddr_t _sbrk(int incr)
{
extern char end asm("end");
static char *heap_end;
char *prev_heap_end;

if (heap_end == 0)
heap_end = &end;

prev_heap_end = heap_end;
if (heap_end + incr > stack_ptr)
{
// write(1, "Heap and stack collision\n", 25);
// abort();
errno = ENOMEM;
return (caddr_t) -1;
}

heap_end += incr;

return (caddr_t) prev_heap_end;
}

So it looks like you will need to provide the start and end address of the heap for it to work correctly, I have seen this done before in the linker file. Unfortunately I don't have a working example but hopefully this helps a little.

BTW if you are using an RTOS it is better to use the memory management provided by that, rather than the C standard (newlib etc).


Return to “Embedded target code development discussions”

Who is online

Users browsing this forum: No registered users and 2 guests