allocating a buffer vs declaring it

chaabanemalki wrote on Tuesday, June 23, 2015:

Hello,

I have task1 calling functionA. what’s the difference between the 2 following cases of fucntionA

Taks1()
{

    for(;;)
    {
        functionA();
    }
}

case 1

functionA()
{
    char* pBuffer;

    pBuffer = pvPortMalloc(100);
    {
        // process data, 
       //pBuffer is always used when calling functionA
    }
    pPortFree(pBuffer );

}

case 2

functionA()
{
    Buffer[60];

        // process data, 
        // buffer is always used when calling functionA
}

If taskA is pre-empted by a higher priority task, Will task1 save the variables of fucntionA ?

What is the best function to use ?

Thank you

rtel wrote on Tuesday, June 23, 2015:

If you declare a local 60 byte array then the compiler will place the array on the stack of the task. Every task has its own stack, so every task will have its own array, so it is a thread-safe way of doing it. This is a fast and neat way of allocating a 60 byte buffer - but it will mean the size of the stack allocated to the task will have to be large enough to hold it. See http://www.freertos.org/Stacks-and-stack-overflow-checking.html

If you dynamically allocate a buffer by calling pvPortMalloc(), and store a pointer to the buffer in a local variable (pBuffer in your case) then that variable will be either on the stack of the task or in a register. Every task has its own stack, and its own pseudo-copy of the registers - so again this is thread safe. Dynamically allocating the buffer is much slower than just declaring an array on the stack, but will allow you to allocate a smaller stack to the task.

Regards.

chaabanemalki wrote on Wednesday, July 01, 2015:

Thank you for the clarification.
So if I understood right. In the example I showed above, case 2 :
the compiler will place and 60 bytes array the stack of task1 and another 60 bytes in the stack of functionA ? am I right ?

woops_ wrote on Wednesday, July 01, 2015:

right

richard_damon wrote on Thursday, July 02, 2015:

In case 1, you have 60 bytes allocated on the task1 stack, so you need to make sure that you give task1 enough stack to store it.

In case 2, you have 60+ bytes allocated on the heap (it is + as allocations on the heap often require some overhead bytes to operate with them, and the allocation is often rounded up to some increment), and a pointer on the stack (likely 2 or 4 bytes long). This means you will need to make sure the heap has enough space to allocate the object out of.