CPP object in new task function memory leak

bearchun
Posts: 2
Joined: Sat Jul 01, 2017 3:52 am

CPP object in new task function memory leak

Postby bearchun » Sat Jul 01, 2017 4:05 am

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.

ESP_igrr
Posts: 2072
Joined: Tue Dec 01, 2015 8:37 am

Re: CPP object in new task function memory leak

Postby ESP_igrr » Sat Jul 01, 2017 6:08 pm

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.

Who is online

Users browsing this forum: No registered users and 53 guests