xTaskCreate returns handle on error

dgheyl wrote on Friday, June 17, 2011:

ATMega644 - WinAVR - FreeRTOS7.0.1
Initially I start only one task and put the micro to sleep.  If the start button is pressed, the micro wakes up and then other tasks are started. If the system is then turned off, those other tasks are deleted by the main task and then it goes back to sleep.  When I start two additional tasks from the main, I can turn it on and off five times - the sixth time doesn’t start properly. If I start only one task, I can turn on/off 10 times before failure.  I found that xTaskCreate is returning errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY - obviously I’m doing something wrong to use up memory. So that is my first issue - what am I doing wrong?  I do not allocate any memory - only have declared variables. I thought maybe I was putting the micro to sleep before the OS had time to clean up, so I added this:
while (1)
num = uxTaskGetNumberOfTasks();
if (num == 2)
vTaskDelay( ( portTickType ) 200 / portTICK_RATE_MS );
It appears to drop to two tasks after one loop, which makes sense - I assume the 2nd task is the Idle task. So that doesn’t appear to be the problem.  Any ideas about why I’m using up memory?  Or is more time needed?

The second issue is that I question whether xTaskCreate is working as expected when it returns errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY. Again using uxTaskGetNumberOfTasks() to look at the number of tasks, it appears that the task was not actually created when the error is returned.  However, it returns a Handle, which I did not expect - assumed it would return 0 for Handle if not created.  I was checking for a non-zero Handle before calling vTaskDelete.  When I did this - tried to delete the tasks that weren’t really created, it ended up deleting all my tasks - uxTaskGetNumberOfTasks() = 0.  Is that how you would expect it to work?

Best Regards,

rtel wrote on Friday, June 17, 2011:

I don’t think what happens to the task handle when a task cannot be created is specified anywhere - but what actually happens is nothing happens.  The task handle is not touched if an error code is returned, so you will get out whatever you put in.

With regards to running out of memory.  See the following link: http://www.freertos.org/a00111.html - you will see that the FreeRTOS heap is used when tasks are created to allocate the task stack and TCB, and that if you are using the very simplest memory manager (heap_1.c) you cannot free memory once it is allocated.  Also see http://www.freertos.org/a00126.html to get an explanation of when the memory that was allocated for the stack and TCB is freed again once the task has been deleted.


dgheyl wrote on Friday, June 17, 2011:


Thanks so much for the quick reply.  I changed to heap_2 and it works fine, of course.  I had built this project on a much simpler earlier project and didn’t think about the memory management.