Quantcast
Viewing all articles
Browse latest Browse all 168

What's wrong with my Heap API commands here?

I read that LocalAlloc and GlobalAlloc are now considered old, and MSDN recommends using Heap functions instead. So I read how to use them and I tried the below. But I'm getting unexpected results, including the VB6 IDE crashing at any time, in an unpredictable manner. Below is my code.

Code:

Private Declare Function HeapCreate Lib "kernel32.dll" (ByVal flOptions As Long, ByVal dwInitialSize As Long, ByVal dwMaximumSize As Long) As Long
Private Declare Function HeapAlloc Lib "kernel32.dll" (ByVal hHeap As Long, ByVal dwFlags As Long, ByVal dwBytes As Long) As Long
Private Declare Function HeapSize Lib "kernel32.dll" (ByVal hHeap As Long, ByVal dwFlags As Long, ByRef lpMem As Any) As Long
Private Declare Function HeapFree Lib "kernel32.dll" (ByVal hHeap As Long, ByVal dwFlags As Long, ByRef lpMem As Any) As Long
Private Declare Function HeapDestroy Lib "kernel32.dll" (ByVal hHeap As Long) As Long

Dim hHeap As Long
Dim ptrHBlock As Long



Private Sub Command1_Click()
MsgBox HeapSize(hHeap, 0, ptrHBlock)
End Sub

Private Sub Form_Load()
hHeap = HeapCreate(0, 1024& * 1024, 0)
ptrHBlock = HeapAlloc(hHeap, 0, 1024)
Print hHeap
Print ptrHBlock
End Sub

Private Sub Form_Unload(Cancel As Integer)
MsgBox HeapFree(hHeap, 0, ptrHBlock)
MsgBox HeapDestroy(hHeap)
End Sub

As you can see, at load-time (in the Form Load event), the 1MB is initially reserved for the heap, without maximum size so that it can expand if needed. Then 1kB is attempted to be allocated from the heap (made accessible for read/write operations), though in actuality it will be rounded up to the nearest page size (which may make it larger than 1kB, depending on the page size on my system).

Then clicking the Command1 button is supposed to return the size in bytes of the allocated heap memory, but here's where things go wrong. It ALWAYS returns 0, which means something is obviously very wrong.

Then when closing, the program the Form Unload event is supposed to free the allocated heap memory block and destroy the created heap. Unfortunately though, the HeapFree command returns 0, which means it failed. And guess what, starting and closing the program a few times causes the VB6 IDE itself to eventually crash (and that's despite making sure to ALWAYS use the X button on the form, so that the Form Unload event is always used, rather than the IDE Stop button). Not sure what's going on here, but there's something funky going on with the heap memory stuff.

Viewing all articles
Browse latest Browse all 168

Trending Articles