Аvr malloc problem

Hello, I'm new to Arduino and Arduino forum and I don't know if this is the right place for my question.

I'm currently implementing library for real-time multi threading for Arduino-avr. Everything works fine except when I try to allocate memory outside the main thread, although I'm locking the current thread while allocating, malloc returns null pointer. I want to ask whether malloc function of avr-gcc, check the current stack pointer in order to validate the available memory? My guess is that the problem is that when the thread manager change the active thread, he set the stack pointer to point the new context. But this context, in most cases is located before the beginning of the free memory which is maintained by malloc (for example, this memory can be part of .bcc or can be dynamically allocated from the heap).

Аnd if so, can you give me advice on how to proceed, if at all there is a way. The easiest way is to forbid the use of malloc, String and similar outside the main thread, but this solution is not very convenient for the users.

Thanks in advance

nickndn: I want to ask whether malloc function of avr-gcc, check the current stack pointer in order to validate the available memory?

Yes.

http://www.nongnu.org/avr-libc/user-manual/malloc.html

jurs: Yes.

http://www.nongnu.org/avr-libc/user-manual/malloc.html

Thank you very much. That link is very useful. As it is written, malloc use __malloc_heap_end as pointer to the end of heap. I could try to change this pointer runtime. When enabling main thread I could change it to 0, and when enabling another thread I could change it to the end of the stack pointer of the main thread. Here comes the question whether the value of __malloc_heap_end can be changed dynamically runtime among 0(auto) and real physical address.