Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C

How to zero your memory?

5.00/5 (1 vote)
9 Aug 2011CPOL 11.8K  
What about this, using SSE2 assembly (32 bits):void Zero(void* Buffer, int Count){ char* Cur= (char*)Buffer; char* End= (char*)Buffer + Count; // Clear the initial unaligned bytes while (Cur < End && (Cur - (char*)0) & 0xf) { *Cur++= 0; } // Clear...

What about this, using SSE2 assembly (32 bits):


C++
void Zero(void* Buffer, int Count)
{
    char* Cur= (char*)Buffer;
    char* End= (char*)Buffer + Count;
    // Clear the initial unaligned bytes
    while (Cur < End && (Cur - (char*)0) & 0xf)
    {
        *Cur++= 0;
    }
    // Clear the full, aligned blocks
    _asm
    {
        pxor xmm0, xmm0;        // 16 zeroes
        mov eax, Cur;
        mov ebx, End;
        and ebx, ~0xf;
While:
        cmp eax, ebx;        // while (Cur < End & ~0xf)
        jnb Wend;
        movapd [eax], xmm0;  // *Cur= 0;
        add eax, 16;         // Cur+= 16;
        jmp While
Wend:
        mov Cur, eax;
    }
    // Clear the final bytes
    while (Cur < End)
    {
        *Cur++= 0;
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)