Null vs ZeroMemory

What is the difference between setting an object to NULL and using ZeroMemory?

I heard that in WinAPI (mostly C) it is a good practice that a person should use ZeroMemory on C objects. I came from C # background and it looks like what a C ++ guy really needs to know.

I found that using the DirectX API, regardless of whether you use ZeroMemory objects or not, the application still works, but some samples use ZeroMemory, and some do not.

Can anyone clarify these things?

+5
source share
7 answers

ZeroMemory fills the memory block with zeros.

NULL , , (, , ).

- , , - - , ZeroMemory .

ZeroMemory , , (, Visual Studio 0x0c0c0c0c/* */, , , , ).

+4

ZeroMemory() 0. . ( ) NULL , 0.

+2

C ++ "" NULL. NULL, , ( " " ).

" ", ZeroMemory(). structs, ++, .

+2

. ZeroMemory . NULL... , .

. , p o "":

struct Type
{
    int i;
    float f;
    bool b;
};
Type o;
Type* p = &o;

// In memory that will be something like this:
// "o" internals = [010101010001010010110010010010100011001001010000011...]
// "p" address = 0x00830748
//(number of bits and hex adress is just example)

ZeroMemory :

ZeroMemory(&o, sizeof(o));
// ---- or -----
ZeroMemory(p, sizeof(o));

// In memory we will have:
// "o" internals = [000000000000000000000000000000000000000000000000000...]
// "p" address = 0x00830748

o 0:

cout << o.i; // 0
cout << o.f; // 0.0f
cout << o.b; // false

cout << p->i; // 0
cout << p->f; // 0.0f
cout << p->b; // false

NUll -ify pointer:

p = NULL;
// In memory we now have:
// "o" internals = [010101010001010010110010010010100011001001010000011...]
// "p" address = 0x00000000

p, undefined:

int a = p->i; // Access voilation reading location 0x00000000

NUll -ify object: , Type =()

o = NULL; // error C2679: binary '=' : no operator found 
          // which takes a right-hand operand of type 'int' 
          // (or there is no acceptable conversion)

DirectX

DirectX , API. . ZeroMemory 0, , , ( - -, ).

+2

ZeroMemory . , "POD" ( ), .

NULL , , "".

ZeroMemory(pointer, sizeof(pointer)); pointer = NULL;, a) , b) , .

0

Zero memory , , , , Null - , ,

0

, id .

// Consider mystuff as being a pointer to an object.
ZeroMemory(mystuff); // Makes this part of memory to be clean
mystuff = NULL; // Makes this pointer point to null so you dont access a 0-memory section.

You can use the DirectX API to allocate memory using malloc, then the call ZeroMemory();will not work as intended. For memory allocated malloc();, you should probably make a call free();. When you work with pointers, I basically set them to NULL right after they are released, idk if this is good practice or not.

0
source

All Articles