I would like to recall my problem with malloc function. Because I didn't receive answer even touching the problem. It's hard for me to understand, that so many people writing to this group are not using malloc function. It's like diving with tied legs and hands. The two things where considred: 1. malloc occupies space of noinit section !! 2. malloc collide with stack after reallocating several times. These faults are serious and should not be avoided. The problems were solved in attached code. Please test it and let me know how is going.
#include <stdlib.h>
#define XSIZE(x) ((*x)>>1) #define FREE_P(x) (!((*x)&1)) #define MARK_BUSY(x) ((*x)|=1) #define MARK_FREE(x) ((*x)&=0xfffe) //extern size_t __bss_end; extern size_t __noinit_end; #define GET_HEAP_BOTTOM(__x) __asm__ __volatile__("mov r1, %0": "=r" ((uint16_t)__x) :) void myfree (void *p); void *mymalloc (size_t size); void *mymalloc (size_t size) { static char once; size_t * heap_bottom; size_t * heap_top = &__noinit_end; size_t * heap_next; size_t xsize; char f = 0; if (!once) { once = 1; *heap_top = 0xFFFE; } GET_HEAP_BOTTOM (heap_bottom); heap_bottom -= 20; size = (size+1) >> 1; /* round to 2 */ do { xsize = XSIZE (heap_top); heap_next = &heap_top[xsize + 1]; if (xsize == 0x7ff)//(xsize<<1)+2 == 0) { f = 1; }else if(heap_next >= heap_bottom){ f = -1; } if (FREE_P (heap_top)) { if (f>0) { xsize = heap_bottom - heap_top - 1; } else if (f < 0){ *heap_top = (heap_bottom - heap_top - 1) << 1; xsize = XSIZE (heap_top); } else if (FREE_P(heap_next)) { *heap_top = ( (XSIZE(heap_next) == 0x7FF)//<<1) + 2 == 0 ? 0xfffe : (xsize + XSIZE(heap_next) + 1)<<1); continue; } if (xsize >= size) { if (f>0) heap_top[size + 1] = 0xfffe; else if (xsize != size) heap_top[size + 1] = (xsize - size - 1) << 1; *heap_top = size << 1; MARK_BUSY (heap_top); return heap_top+1; } } heap_top += xsize + 1; } while (!f); return NULL; } void myfree (void *p) { size_t *t = (size_t*)p - 1; MARK_FREE (t); }