0
0
FreeRTOSprogramming~5 mins

pvPortMalloc and vPortFree in FreeRTOS

Choose your learning style9 modes available
Introduction

pvPortMalloc and vPortFree help you get and give back memory safely in FreeRTOS. They manage memory so your program runs smoothly without crashes.

When you need to create a new task or buffer dynamically during program run.
When you want to allocate memory for data structures like queues or stacks.
When you want to free memory that is no longer needed to avoid wasting space.
When you want to avoid memory conflicts in a multitasking environment.
When you want to use FreeRTOS's built-in memory management instead of standard C malloc/free.
Syntax
FreeRTOS
void *pvPortMalloc(size_t xSize);
void vPortFree(void *pv);

pvPortMalloc returns a pointer to a block of memory of size xSize bytes.

vPortFree frees the memory block pointed to by pv that was previously allocated by pvPortMalloc.

Examples
This allocates 100 bytes of memory and stores the pointer in buffer.
FreeRTOS
char *buffer = (char *)pvPortMalloc(100);
This frees the memory previously allocated and pointed to by buffer.
FreeRTOS
vPortFree(buffer);
Allocates memory for an array of 10 integers.
FreeRTOS
int *numbers = (int *)pvPortMalloc(10 * sizeof(int));
Sample Program

This program shows how to allocate memory for 5 integers using pvPortMalloc, fill the array, print the values, and then free the memory with vPortFree.

FreeRTOS
#include "FreeRTOS.h"
#include "task.h"
#include <stdio.h>

int main(void) {
    // Allocate memory for 5 integers
    int *data = (int *)pvPortMalloc(5 * sizeof(int));
    if (data == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    // Use the allocated memory
    for (int i = 0; i < 5; i++) {
        data[i] = i * 10;
    }

    // Print the values
    for (int i = 0; i < 5; i++) {
        printf("data[%d] = %d\n", i, data[i]);
    }

    // Free the memory
    vPortFree(data);

    return 0;
}
OutputSuccess
Important Notes

Always check if pvPortMalloc returns NULL, which means memory allocation failed.

Use vPortFree to avoid memory leaks by freeing memory you no longer need.

These functions are thread-safe and designed for FreeRTOS multitasking environments.

Summary

pvPortMalloc gets memory safely in FreeRTOS.

vPortFree gives back memory to avoid waste.

Use them to manage memory in multitasking programs.