잠토의 잠망경

VirtualAlloc & VirtualFree 본문

공부/API

VirtualAlloc & VirtualFree

잠수함토끼 2008. 9. 6. 22:59

대용량의 메모리의 경우 VirtualAlloc을 사용하는 것이 바람직하나,
작은 용량의 메모리를 사용하는 경우 realloc을 사용하는 것이 바람직하다.

Windows API 정복 P1485

#undef UNICODE

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

#define MEGA 1024*1024

PBYTE stptr;
PBYTE endptr;
PBYTE nowptr;


void FreeRecodes()
{
 if(stptr!=NULL)
 {
  if(VirtualFree(stptr,100*MEGA,MEM_DECOMMIT)==0){
   MessageBox(NULL,"메모리 확정 해제 실패","에러",MB_OK);
  }
  if(VirtualFree(stptr,100*MEGA,MEM_RELEASE)==0){
   MessageBox(NULL,"메모리 예약 해제 실패","에러",MB_OK);
  }
  stptr=NULL;
 }
 printf("할당이 해제 되었습니다.");
}

void ReadRecoders()
{
 int i, c;
 int RecSize;
 //기존에 할당을 했던것이 있다면 먼저 해제를 하고 시작을 한다.
 FreeRecodes();
 //가상주소공간(virtual Address Space)에 메모리를 할당을 한다.
 stptr=(PBYTE)VirtualAlloc(NULL,100*MEGA,MEM_RESERVE,PAGE_READWRITE);
 if(stptr==NULL){
  printf("메모리 할당이 실패하였습니다.");
  return;
 }
 //메모리의 위치를 초기화 시켜준다.
 endptr=stptr;
 nowptr=stptr;
 
 //C는 10~99 값을 갖는다.
 c=rand()%90+10;
 printf("loop Count: %d\n",c);
 for(i=0;i<c;i++)
 {
  if(endptr-nowptr<MEGA){
   //현재 남은 영역이 1MB이하일 경우 추가로 쓸영역을 commit 한다.
   VirtualAlloc(endptr,MEGA,MEM_COMMIT,PAGE_READWRITE);
   endptr+=MEGA;//1MB 만큼 end pointer를 이동시켜준다.
  }

  RecSize=((rand()%100)+1)*10240;//랜덤으로 초기화할 사이즈를 할당한다.
  memset(nowptr,i,RecSize);//memset을 사용하여 현재 i의 값으로 채운다.
  nowptr+=RecSize;
  printf("Use Size: %d\n", RecSize);
 }

 printf("예약: 100메가, commit: %d, 사용: %d\n",
  (endptr-stptr)/MEGA, (nowptr-stptr)/MEGA);
}

int main(void)
{
 ReadRecoders();
 return 0;
}

Comments