Page 1 of 1

CPP object in new task function memory leak

Posted: Sat Jul 01, 2017 4:05 am
by bearchun
I'm using ESP-IDF release v2.1 (rc) with CPP code.

When I create a new TASK and use CPP objects like this then exit the task code I get a memory leak:

Code: Select all

void vATaskFunction( void *pvParameters )
{
    string s = "hello";
    vector<int> v;
    vTaskDelete(NULL);
}
This DOES NOT leak memory:

Code: Select all

void vATaskFunction( void *pvParameters )
{
    string* s = new string("hello");
    vector<int>* v = new vector<int>();
    delete s;
    delete v;
    vTaskDelete(NULL);
}
And this work around DOES NOT leak memory:

Code: Select all

void helper( void *pvParameters )
{
    string s = "hello";
    vector<int> v;
}
void vATaskFunction( void *pvParameters )
{
    helper(pvParameters);
    vTaskDelete(NULL);
}
Is this expected behavior? Am I the only one getting this problem?

Every time I create a new task, I was getting a massive memory leak and later I found out it was caused by this weird behavior.

Re: CPP object in new task function memory leak

Posted: Sat Jul 01, 2017 6:08 pm
by ESP_igrr
This is an original FreeRTOS behavior, and I don't think there is a way around it, without changing the design. When vTaskDelete is called, task execution is stopped, and the task function never returns. Therefore variables which have been declared inside task function don't go out of scope, hence destructors are not called and memory is not released (except for the automatic storage on the stack, which gets released when the stack is deleted.

Wrapping your c++ code with another function (which shouldn't call vTaskDelete) or even placing it into { } scope within the task function should be enough to work around this.