ARF ARF - 1 year ago 83
C Question

What is zalloc in embedded programming?

I am looking into programming the ESP8266 serial-wifi chip. In its SDK examples it makes extensive use of a function called

where I would expect

Occasionally though,
is used as well. So they do not appear to be identical in function.

Unfortunately there is no documentation. Can anybody make an educated guess from the following header file?

#ifndef __MEM_H__
#define __MEM_H__

//void *pvPortMalloc( size_t xWantedSize );
//void vPortFree( void *pv );
//void *pvPortZalloc(size_t size);

#define os_malloc pvPortMalloc
#define os_free vPortFree
#define os_zalloc pvPortZalloc


Answer Source

Since os_zalloc is a macro, and the definition is given in mem.h, a better question to ask would be about what pvPortZalloc does.

Given the function names pvPortMalloc, vPortFree and pvPortZalloc it would appear that the OS in use is FreeRTOS (or it's commercially licensed equivalent OpenRTOS), which is documented - although not specifically pvPortZalloc, but it would be strange if it was not simply allocate and zero initialise - that is for example what it means here. The functions are part of the target porting layer for FreeRTOS, and are not normally called by the application level, but I imagine here the macro wrapper is used to access the porting layer code for application user rather than write it twice.

In an RTOS kernel RTOS aware dynamic memory allocation functions are required to ensure thread safety, although some standard library implementations include thread safety stubs that you implement using the RTOS mutex calls, which is a better method since existing libaries and C++ new/delete can be more easily used.