Programming Tips - C/C++: What's the best way (in win32) to clear memory?

Date: 2004aug22 Update: 2026sep17 Platform: win32 Language: C/C++ Q. C/C++: What's the best way (in win32) to clear memory? A. In ye olden days I used to code:
memset(&myStruct, 0, sizeof(myStruct));
Now I write:
ZeroMemory(&myStruct, sizeof(myStruct));
Which is one character longer but reads nicer. This is defined in the Win32 headers as:
#define ZeroMemory(Destination,Length) memset((Destination),0,(Length))
Linux has:
bzero(&myStruct, sizeof(myStruct));
Sadly bzero is deprecated so you can define it:
#ifndef bzero #define bzero(_d, _n) memset((_d), 0, (_n)) #endif
If you have a newer compiler you can do:
char buf[100] = {}
To zero an array or struct. Example Use:
#include <string.h> #include <stdio.h> struct MyStruct { int a; int b; }; int main() { // // Testing memset() // { MyStruct myStruct; // Set them to non-zero myStruct.a = 111; myStruct.b = 222; memset(&myStruct, 0, sizeof(myStruct)); printf("zeroed with memset()\n"); printf("myStruct.a=%d\n", myStruct.a); printf("myStruct.b=%d\n", myStruct.b); } // // Testing = {} // { MyStruct myStruct = {}; printf("\n"); printf("zeroed with = {}\n"); printf("myStruct.a=%d\n", myStruct.a); printf("myStruct.b=%d\n", myStruct.b); } }
Output:
zeroed with memset() myStruct.a=0 myStruct.b=0 zeroed with = {} myStruct.a=0 myStruct.b=0