title: JNA Memory Leak - How to fix?
body: <pre><code>        public static User32 USER32_INSTANCE = (User32) Native.loadLibrary("user32", User32.class);
  
          user32 = USER32_INSTANCE;
  
          user32.EnumWindows((hWnd, arg) -&gt; {
            int size = 1024 * 8;
            char[] buffer = new char[size];
            USER32_INSTANCE.GetWindowTextW(hWnd, buffer, size);
  
            char[] buffer2 = new char[size];
            PointerByReference pointer = new PointerByReference();
            User32DLL.GetWindowThreadProcessId(hWnd, pointer);
            Pointer process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pointer.getValue());
            Psapi.GetModuleBaseNameW(process, null, buffer2, size);
  
            String result = Native.toString(buffer).trim();
            String proc = Native.toString(buffer2).trim();
  
            // ... (non-JNA stuff)
          }
  </code></pre>
  
  <p>I haven't touched C/C++ since college and I honestly have no clue how to actually free the memory here :( </p>
  
  <p>I know that there's a memory leak - I did some profiling with YourKit and traced a memory leak to this block of code (specifically, it seems to be leaking in the GetWindowTextW call and the Native.toString() calls). Could someone just give me an example of how to properly free up whatever memory blocks are being used? </p>
  
  <p>I see that <code>Pointer</code> has a <code>clear()</code> method, should I use that? But I don't know how to get the size (<code>clear</code> takes a length argument). I also see that there's a <code>Memory</code> type that subclasses <code>Pointer</code>, but according to <code>instanceof</code>, none of the Pointers I have right now are actually instances of that.</p>