공부

VirtualAlloc 함수를 이용한 Dynamic Array Design

글로벌디노 2020. 8. 15. 18:05

VirtualAlloc 함수를 이용해서 메모리 예약, 커밋, 해제를 직접 사용해보자

 

#include <stdio.h>
#include <Windows.h>

SIZE_T maxPage = 10;
SIZE_T pageCount = 0;
SYSTEM_INFO si;
LPVOID baseAddr;

int PageFaultExceptionFilter(DWORD);

int main()
{
	GetSystemInfo(&si);

	baseAddr = VirtualAlloc(
		NULL, 
		si.dwPageSize * maxPage,
		MEM_RESERVE, 
		PAGE_NOACCESS);

	int dataSize = (si.dwPageSize * maxPage) / sizeof(int);
	int* dataArr = (int*)baseAddr;
	for (int i = 0; i < dataSize; i++)
	{
		__try
		{
			dataArr[i] = i;
		}
		__except (PageFaultExceptionFilter(GetExceptionCode()))
		{
			ExitProcess(GetLastError());
		}

		Sleep(0);
	}

	return 0;
}

int PageFaultExceptionFilter(DWORD exptCode)
{
	// 예외 원인이 page fault 가 아니라면
	if (exptCode != EXCEPTION_ACCESS_VIOLATION)
	{
		printf_s("Exception Code = %d \n", exptCode);
		return EXCEPTION_EXECUTE_HANDLER;
	}

	printf_s("Exception is a page fault \n");

	if (pageCount >= maxPage)
	{
		printf_s("Out of Page \n");
		return EXCEPTION_EXECUTE_HANDLER;
	}

	void* nextPageAddr = (char*)baseAddr + si.dwPageSize * pageCount;
	LPVOID result = VirtualAlloc(
		nextPageAddr,
		si.dwPageSize,
		MEM_COMMIT,
		PAGE_READWRITE
	);

	if (result == NULL)
	{
		printf_s("VirtualAlloc fail \n");
		return EXCEPTION_EXECUTE_HANDLER;
	}
	else
	{
		printf_s("Allocating another page. \n");
	}

	pageCount++;

	return EXCEPTION_CONTINUE_EXECUTION;
}

 

반응형