Click here to Skip to main content
Click here to Skip to main content

Safe way to erase memory in C++

, 14 Jan 2013
Rate this:
Please Sign up or sign in to vote.
Safe way to set memory to zeroes in C++11

To initialize all the bytes to zeroes, we can use the shortcut syntax (={}) below.

#include <iostream>

typedef struct tagMyStruct
{
    int a;
    short b;
    char c;
} MyStruct;

void DisplayStruct(MyStruct& my)
{
    std::cout << my.a << "," << my.b << "," << (int)my.c << std::endl;
}

void main()
{
    MyStruct st = {};
    DisplayStruct(st); // display all zeroes
} 

In C++11, we can use uniform initialization that eliminates the assignment operator.

MyStruct st{};
DisplayStruct(st);

If developer need to erase memory after it has been used, his/her only option is memset or ZeroMemory. The problem with these 2 functions, is programmer could specify the incorrect length of memory which carries the risk of buffer overrun or erasing only part of the array. This tip introduces 2 simple template functions to help, namely ZeroOut and ZeroOutPtrArray. ZeroOut is used for stack variables of primitive types or structure of primitive types or array of these 2 types while ZeroOutPtrArray is used for pointer that points to an array which could be on the stack or heap. The definition of ZeroOut is listed below.

template<typename T>
void ZeroOut(T& t)
{
    static_assert(std::is_pointer<T>::value == false, 
        "Error: Please use ZeroOutPtrArray for pointer-to-array");

    std::memset(&t, 0, sizeof(T));
}

ZeroOut makes use of static_assert to check if a pointer is passed in and puts out a compile-time error which tells the programmer to use ZeroOutPtrArray instead. Here is an example on how to use ZeroOut.

MyStruct st = { 12, 13, 'c'};
DisplayStruct(st); // display 12, 13, 99
ZeroOut(st);
DisplayStruct(st); // display all zeroes

ZeroOut also works for array on stack.

MyStruct arr[5];

for(size_t i=0; i<5; ++i)
    DisplayStruct(arr[i]); // display rubbish

ZeroOut(arr);

for(size_t i=0; i<5; ++i)
    DisplayStruct(arr[i]); // display all zeroes

The definition of ZeroOutPtrArray is stated below. With ZeroOutPtrArray, the caller needs to specify the number of elements in the array, unlike ZeroOut. For example of array of 4 integers, the count is 4.

template<typename T>
void ZeroOutPtrArray(T* t, size_t count)
{
    std::memset(t, 0, sizeof(T)*count);
}

Here is an example on how to use ZeroOutPtrArray.

MyStruct* p = new MyStruct[5];

for(size_t i=0; i<5; ++i)
    DisplayStruct(p[i]); // display rubbish

ZeroOutPtrArray(p, 5);

for(size_t i=0; i<5; ++i)
    DisplayStruct(p[i]); // display all zeroes

delete [] p;

Windows compiler has been known to optimize away the memset call in release build when it detected that the array is no longer accessed afterwards. In that case, feel free to replace the memset with SecureZeroMemory which is guaranteed not to be optimized away. however do note that SecureZeroMemory is a macro in Winbase.h header while memset is a standard function in string.h(C) or cstring.h(C++), therefore memset is portable.

The code snippets have been tested to be worked with GCC 4.7.2 and Clang 3.2. Please be noted that static_assert is only supported on Visual C++ 10 (VS2010) and above.

License

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

About the Author

SV Wong
Software Developer
Singapore Singapore

Currently into areas like 3D graphics and application security. Hoping to revisit the cryptography and design pattern topics if time permits.


Comments and Discussions

 
Questionwhy? PinmemberK0t418-Jan-13 7:50 
AnswerRe: why? PinmemberWong Shao Voon30-Jan-13 20:17 
GeneralMy vote of 4 Pinmemberhardben17-Jan-13 0:17 
Good for me!

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 15 Jan 2013
Article Copyright 2013 by SV Wong
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid