cancel
Showing results for 
Search instead for 
Did you mean: 

SPC5Studio cannot use the malloc() and free() functions in the stdlib.h standard library.

ZhangXR
Associate II

SPC5Studio cannot use the malloc() and free() functions in the stdlib.h standard library.

For Example:

char * str = (char *) malloc(1024);
free(str);

I've added the GCC standard header path to SPC5Studio, and other library functions are used normally, and I can't compile through when using the malloc function, reporting the following error:

c:/spc5studio/eclipse/plugins/com.st.tools.spc5.tools.gnu.gcc.ppcvle.win32_4.9.4.20190604105544/toolchain/bin/../lib/gcc/powerpc-eabivle/4.9.4/../../../../powerpc-eabivle/lib\libc.a(lib_a-sbrkr.o): In function `_sbrk_r':
sbrkr.c:(.text._sbrk_r+0x1a): undefined reference to `sbrk'
collect2.exe: error: ld returned 1 exit status
make: *** [build/out.elf] Error 1

How do I solve the problem that malloc and free are not available, or how do I dynamically allocate memory in SPC5Studio?

Thank you.

1 ACCEPTED SOLUTION

Accepted Solutions
Erwan YVIN
ST Employee

Hello Zhang ,

you can create a sbrk function in your code.

Do not forget to free the pointer.

/*
 * ---------------------------------------------------------------------------------------------------
 *
 *---------------------------------------------------------------------------------------------------
 */
 
void *sbrk(size_t incr) {
  extern uint8_t __heap_base__;
  extern uint8_t __heap_end__;
  static uint8_t *p = &__heap_base__;
  static uint8_t *newp;
 
  newp = p + incr;
  if (newp > &__heap_end__) {
    errno = ENOMEM;
    return (void *)-1;
  }
  return p = newp;
}

Best regards

Erwan

View solution in original post

4 REPLIES 4

Assume you'll have to create an allocator if not in a syscall.c or newlibs.c file

https://codereview.stackexchange.com/questions/226231/implementing-sbrk-for-a-custom-allocator-in-c

Tips, buy me a coffee, or three.. PayPal Venmo Up vote any posts that you find helpful, it shows what's working..

Hello,

My project doesn't have an RTOS, so I don't have a syscall.c file. Can you explain in detail how I can use the malloc function?

Thank you.

Erwan YVIN
ST Employee

Hello Zhang ,

you can create a sbrk function in your code.

Do not forget to free the pointer.

/*
 * ---------------------------------------------------------------------------------------------------
 *
 *---------------------------------------------------------------------------------------------------
 */
 
void *sbrk(size_t incr) {
  extern uint8_t __heap_base__;
  extern uint8_t __heap_end__;
  static uint8_t *p = &__heap_base__;
  static uint8_t *newp;
 
  newp = p + incr;
  if (newp > &__heap_end__) {
    errno = ENOMEM;
    return (void *)-1;
  }
  return p = newp;
}

Best regards

Erwan

Hello Erwan,

Problem solved, compiled and approved, thank you very much!

​Best regards

ZhangXR