본문 바로가기
프로그래밍 언어/C, C++

[C/C++] 메모리 초기화하기: ZeroMemory 매크로

by 니키티스 2023. 8. 6.

윈도우 프로그래밍에서 맨날 메모리를 0으로 초기화할 때 memset은 안 쓰고 ZeroMemory를 쓴다.

ZeroMemory

ZeroMemory는 매크로의 일종으로 정의는 다음과 같다.

// minwinbase.h
#define MoveMemory RtlMoveMemory
#define CopyMemory RtlCopyMemory
#define FillMemory RtlFillMemory
#define ZeroMemory RtlZeroMemory

// winnt.h
#define RtlEqualMemory(Destination,Source,Length) (!memcmp((Destination),(Source),(Length)))
#define RtlMoveMemory(Destination,Source,Length) memmove((Destination),(Source),(Length))
#define RtlCopyMemory(Destination,Source,Length) memcpy((Destination),(Source),(Length))
#define RtlFillMemory(Destination,Length,Fill) memset((Destination),(Fill),(Length))
#define RtlZeroMemory(Destination,Length) memset((Destination),0,(Length))

그냥 단순하게, 지정된 주소(dest)에 길이(length)만큼 memset으로 바이트 단위로 0으로 채워주는 역할을 한다.

사용할 땐 ZeroMemory([목표 주소], [길이]) 꼴로 쓴다.

배열이나 구조체 등을 초기화할 때 자주 사용한다.

예시

struct exampleStruct
{
	int a;
	int b;
	int c;
}

struct exampleStruct exStruct;
ZeroMemory(&exStruct, sizeof(exStruct));

memset의 정의

memset은 다음과 같이 정의된다.

#include <string.h> // C++ 에서는 <cstring>
void* memset ( void* ptr, int value, size_t num );

참고: ZeroMemory와 memset() 함수 - 메모리 블록 채우기 (tistory.com)

댓글