Repeat "new delete" operator cause heap overflow

your answer is hard to understand.

I’m sorry for that. In the example below three static arrays of bytes (threadStack0, threadStack1 and threadStack2) are allocated in order to be used as Thread stacks. Then a Thread daemon is created in the static memory (array of bytes) threadStack0. When the daemon is not needed anymore it is deleted and a new Thread myThread is created in the same static memory (array of bytes) threadStack0. The other two arrays (threadStack1 and threadStack2) are not utilized in this example (you can delete them to use less SRAM):

#include "mbed.h"

#define THREAD_STACK_SIZE   OS_STACK_SIZE * 2

DigitalOut  led1(LED1);
uint8_t     threadStack0[THREAD_STACK_SIZE];    // static memory to be used as thread stack
uint8_t     threadStack1[THREAD_STACK_SIZE];    // static memory to be used as thread stack
uint8_t     threadStack2[THREAD_STACK_SIZE];    // static memory to be used as thread stack
Thread*     daemon;
Thread*     myThread;

void taskDaemon()
{
    while (1) {
        printf("Task daemon\r\n");
        ThisThread::sleep_for(500ms);
    }
}

void taskMyThread()
{
    while (1) {
        printf("Task myThread\r\n");
        ThisThread::sleep_for(500ms);
    }
}

int main()
{
    int count = 0;

    daemon = new Thread(osPriorityNormal, THREAD_STACK_SIZE, threadStack0, "host"); // create a thread at threadStack0
    daemon->start(callback(taskDaemon));

    while (true) {
        led1 = !led1;
        ThisThread::sleep_for(500);
        count++;
        if (count == 10) {
            osStatus    status = daemon->terminate();
            if (status == osOK) {
                delete daemon;
                myThread = new Thread(osPriorityNormal, THREAD_STACK_SIZE, threadStack0, "my_thread");  // create a thread at threadStack0
                myThread->start(callback(taskMyThread));
            }
        }
    }
}

This thread could be useful too.