Skip to content
This repository was archived by the owner on Mar 31, 2026. It is now read-only.

Protected Heap Allocation Functions

kping0 edited this page Jun 26, 2018 · 2 revisions

Server Heap Allocation

Configuration

The server has the option to use protected heap allocation functions.

These functions (declared in "include/protected_malloc.h") are called sscs_cmalloc() and sscs_cfree(). However, to allow flexibility in configuration, they are defined as cmalloc() and cfree() (as seen here).

/* protected_malloc.h */
#define cmalloc(size) sscs_cmalloc(size,__FILE__,__LINE__) 
#define cfree(ptr) sscs_cfree(ptr,__FILE__,__LINE__)

However, if a user does not want his server using protected allocation functions, he can comment out the SSCS_CUSTOM_MALLOC definition, which binds cmalloc() and cfree() to calloc() and free() (system specific).

/* settings.h */
// #define SSCS_CUSTOM_MALLOC 
#ifdef SSCS_CUSTOM_MALLOC
    #include "protected_malloc.h"
#else
    #define cmalloc(size) calloc(1,size) 
    #define cfree(ptr) free(ptr) 
    /* ... */

Memory layout & overhead using the protected allocation functions

This is the memory layout of an allocated block on the heap:

/*
 * -------------------------------------------------------------------------------------------------
 * | MAGIC | CHKVAR | SIZEOF_BUFFER | 0x0 | USABLE_BUFFER | 0x0 | CHKVAR | MAGIC | ... | GUARDPAGE |
 * -------------------------------------------------------------------------------------------------
 * |  4B   |   8B   |      8B       |  1B |     USRDEF    | 1B  |   8B   |  4B   | VAR |   4096B   | 
 * -------------------------------------------------------------------------------------------------
 */

NOTE: this results in a memory overhead per allocation of ~4-8 KB overhead (setting up a guardpage requires the memory to be aligned, meaning we have to allocate a multiple of the system pagesize) so allocating huge buffers is more effective, while allocating small buffers is VERY inefficient ( cmalloc(20) results in around 8KB being allocated )

Clone this wiki locally