Why do ZeroMemory, etc. exist when there are memset, etc. already?

前端 未结 8 1061
萌比男神i
萌比男神i 2020-12-10 00:55

Why does ZeroMemory(), and similar calls exist in the Windows API when there are memset and related calls in the C standard library already? Which ones should I

相关标签:
8条回答
  • 2020-12-10 01:23

    In C and C++, ZeroMemory() and memset() are the exact same thing.

    /* In winnt.h */
    #define RtlZeroMemory(Destination,Length) memset((Destination),0,(Length))
    
    /* In winbase.h */
    #define ZeroMemory RtlZeroMemory
    

    Why use ZeroMemory() then? To make it obvious. But I prefer memset() in C or C++ programs.

    0 讨论(0)
  • 2020-12-10 01:25

    Because, ZeroMemory don't require line of comment

    0 讨论(0)
  • 2020-12-10 01:27

    The actual reason is that on a different platform it might be implemented in a more efficient way than memset. Don't forget that Windows NT was designed as a highly portable operating system, it actually ran on Alpha, MIPS and Power PC. So, if the fooPC platform came out and has some assembly way to ultra-fast set memory to zero, it can be implemented without changing the high level API. This is no longer true for Windows, since now it only supports x86 and amd64 platforms, however it is still true for Windows CE.

    0 讨论(0)
  • 2020-12-10 01:31

    Actually, what you want to use is SecureZeroMemory().

    An optimizing compiler can remove calls to memset(), and SecureZeroMemory() is designed to prevent this.

    I used to think the ZeroMemory() calls were unnecessary until I came across this fact.

    0 讨论(0)
  • 2020-12-10 01:31

    I think one point is that the memory allocation functions should look the same in all Win32 projects, independent of the programming language. Indeed, as have been pointed out before, in C, ZeroMemory is actually memset, the C function. In Delphi,

    procedure ZeroMemory(Destination: Pointer; Length: DWORD);
    begin
      FillChar(Destination^, Length, 0);
    end;
    

    where FillChar is the Delphi function. And so on:

    procedure MoveMemory(Destination: Pointer; Source: Pointer; Length: DWORD);
    begin
      Move(Source^, Destination^, Length);
    end;
    
    procedure FillMemory(Destination: Pointer; Length: DWORD; Fill: Byte);
    begin
      FillChar(Destination^, Length, Fill);
    end;
    
    ...
    
    0 讨论(0)
  • 2020-12-10 01:34

    According to MSDN, ZeroMemory is a macro. It probably exists as a convenience (e.g., naming convention) or for backwards compatibility.

    0 讨论(0)
提交回复
热议问题