2020-08-17 06:49 PM
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.
Solved! Go to Solution.
2020-08-18 02:19 AM
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
2020-08-17 07:14 PM
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
2020-08-17 08:22 PM
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.
2020-08-18 02:19 AM
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
2020-08-18 06:44 PM
Hello Erwan,
Problem solved, compiled and approved, thank you very much!
Best regards
ZhangXR