본문 바로가기
C++ 200제/코딩 IT 정보

[C#] 동적메모리 할당 해제 소스 코드 예제 (malloc)

by vicddory 2017. 11. 6.

[C#] 동적메모리 할당 해제 소스 코드 예제 (malloc)


동적메모리 할당 해제 소스 코드, C# 강좌[[C#] 동적메모리 할당 해제 소스 코드 예제 (malloc)]


동적메모리 사용을 위한 예제가 MSDN에 있어서 퍼왔습니다. C#에서는 stackalloc 연산자라는 메모리 관리 구문이 있습니다. 그리고 가비지 컬렉터도 동적메모리 할당, 해제 구문을 갖고 있습니다.


일반적으로 이러한 서비스(동적메모리 할당 해제)는 해당 클래스 라이브러리에서 제공하거나 운영체제에 구현되어 있습니다. 아래 예제는 동적메모리 할당을 위해 운영체제의 힙 함수를 엑세스합니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using System;
using System.Runtime.InteropServices;
 
public unsafe class Memory
{
   // Handle for the process heap. This handle is used in all calls to the
   // HeapXXX APIs in the methods below.
   static int ph = GetProcessHeap();
 
   // Private instance constructor to prevent instantiation.
   private Memory() {}
 
   // Allocates a memory block of the given size. The allocated memory is
   // automatically initialized to zero.
   public static void* Alloc(int size) {
      void* result = HeapAlloc(ph, HEAP_ZERO_MEMORY, size);
      if (result == nullthrow new OutOfMemoryException();
      return result;
   }
 
   // Copies count bytes from src to dst. The source and destination
   // blocks are permitted to overlap.
   public static void Copy(void* src, void* dst, int count) {
      byte* ps = (byte*)src;
      byte* pd = (byte*)dst;
      if (ps > pd) {
         for (; count != 0; count--*pd++ = *ps++;
      }
      else if (ps < pd) {
         for (ps += count, pd += count; count != 0; count--*--pd = *--ps;
      }
   }
 
   // Frees a memory block.
   public static void Free(void* block) {
      if (!HeapFree(ph, 0, block)) throw new InvalidOperationException();
   }
 
   // Re-allocates a memory block. If the reallocation request is for a
   // larger size, the additional region of memory is automatically
   // initialized to zero.
   public static void* ReAlloc(void* block, int size) {
      void* result = HeapReAlloc(ph, HEAP_ZERO_MEMORY, block, size);
      if (result == nullthrow new OutOfMemoryException();
      return result;
   }
 
   // Returns the size of a memory block.
   public static int SizeOf(void* block) {
      int result = HeapSize(ph, 0, block);
      if (result == -1throw new InvalidOperationException();
      return result;
   }
 
   // Heap API flags
   const int HEAP_ZERO_MEMORY = 0x00000008;
 
   // Heap API functions
   [DllImport("kernel32")]
   static extern int GetProcessHeap();
 
   [DllImport("kernel32")]
   static extern void* HeapAlloc(int hHeap, int flags, int size);
 
   [DllImport("kernel32")]
   static extern bool HeapFree(int hHeap, int flags, void* block);
 
   [DllImport("kernel32")]
   static extern void* HeapReAlloc(int hHeap, int flags,
      void* block, int size);
    
   [DllImport("kernel32")]
   static extern int HeapSize(int hHeap, int flags, void* block);
}
cs


C#, 동적메모리를 구현한 Memory 클래스를 사용하는 예제는 다음과 같습니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Test
{
   static void Main() {
      unsafe {
         byte* buffer = (byte*)Memory.Alloc(256);
         try {
            for (int i = 0; i < 256; i++) buffer[i] = (byte)i;
            byte[] array = new byte[256];
            fixed (byte* p = array) Memory.Copy(buffer, p, 256); 
         }
         finally {
            Memory.Free(buffer);
         }
         for (int i = 0; i < 256; i++Console.WriteLine(array[i]);
      }
   }
}
cs


C# 메모리 관리 열심히 하세요~


[C#] 동적메모리 할당 해제 소스 코드 예제 (malloc)

댓글