Programming Pearls: malloc, the Zabbix way

The Zabbix sources define zbx_malloc in include/common.h: line 700 as:

#define zbx_malloc(old, size)   zbx_malloc2(__FILE__, __LINE__, old, size)

zbx_malloc2 is defined in src/libs/zbxcommon/misc.c: line 255 as:

void    *zbx_malloc2(const char *filename, int line, void *old, size_t size)
    int max_attempts;
    void    *ptr = NULL;

    /* old pointer must be NULL */
    if (NULL != old)
        zabbix_log(LOG_LEVEL_CRIT, "[file:%s,line:%d] zbx_malloc: " 	
				"allocating already allocated memory. "
                "Please report this to Zabbix developers.",
                filename, line);
        /* exit if defined DEBUG, ignore otherwise */

    for (
        max_attempts = 10, size = MAX(size, 1);
        0 < max_attempts && NULL == ptr;
        ptr = malloc(size), max_attempts--

    if (NULL != ptr)
        return ptr;

    zabbix_log(LOG_LEVEL_CRIT, "[file:%s,line:%d] zbx_malloc: out of memory."
		"Requested " ZBX_FS_SIZE_T " bytes.",
            filename, line, (zbx_fs_size_t)size);


So where're the pearls in this?

  1. the old parameter is forced to be NULL, so why pass it at all???

  2. noticed the for loop? It tries to malloc ten times before giving up. This seems to assume that some concurrently running part of zabbix frees memory, or that the system suddenly (while this loop is running, that is) assigns a higher memory bound for zabbix.

  3. noticed the MAX in the for loop? It tries to catch and disguise the error of requesting zero bytes by always returning at least one byte

Fri, 05 Apr 2013
[/osfail] permanent link