Search code examples
objective-ccmacossecuritymemset

Mac OS X equivalent of SecureZeroMemory / RtlSecureZeroMemory?


Is there a Mac OS X equivalent of RtlSecureZeroMemory / SecureZeroMemory, a function which zeroes a block of memory, but the call will not be optimized away by the compiler?


Solution

  • Write your own function:

    void secure_zero(void *s, size_t n)
    {
        volatile char *p = s;
    
        while (n--) *p++ = 0;
    }
    

    EDIT: to the question in the comments, why not memset? The memset function call could be optimized away by the compiler if the array object is no futher accessed.

    Note that C11 adds the (optional) function memset_s and the Standard guarantees the function call cannot be optimized away:

    (C11, K.3.7.4.1p4) "[...] Unlike memset, any call to the memset_s function shall be evaluated strictly according to the rules of the abstract machine as described in (5.1.2.3). That is, any call to the memset_s function shall assume that the memory indicated by s and n may be accessible in the future and thus must contain the values indicated by c."