The Shœstring Foundation Weblog
   


About
The Shœstring Foundation Weblog, Miscellaneous Byproducts

Matthias Bauer
bauerm (at) shoestringfoundation · org
reop pubkey
Vignettes by George Herriman and a small program

Subscribe to a syndicated feed of my weblog, brought to you by the wonders of RSS.


Blosxom Logo

       
Fri, 05 Apr 2013

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 */
        zbx_dbg_assert(0);
    }

    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);

    exit(FAIL);
}

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

[/osfail] permanent link