The MASM Forum Archive 2004 to 2012

General Forums => The Campus => Topic started by: 44mag on April 09, 2012, 12:08:16 AM

Title: HeapAlloc pointer usage question
Post by: 44mag on April 09, 2012, 12:08:16 AM
I'm not sure what to do with the pointer received after allocating a block of mem:


.data?
buffer db 64 dup(?)
hMem DWORD ?
pMem DWORD ?

...
...

.elseif uMsg==WM_CREATE

   invoke HeapCreate,HEAP_GENERATE_EXCEPTIONS,64,NULL
   mov hMem,eax
   invoke HeapAllocate,hMem,HEAP_GENERATE_EXCEPTIONS,32
   mov pMem,eax


So I'm guessing now the addr of pMem points to an addr that points to an allocated block of memory?   :dazzled:  Or am I making it more complicated than it really is?  Is there a way I can just change the address of pMem to the addr it contains so I use it like my buffer array?  Thanks for any info!
Title: Re: HeapAlloc pointer usage question
Post by: Twister on April 09, 2012, 12:18:51 AM
Correct. The return value, if it is not null, is the beginning address of the memory block. Also, be sure to free the allocated memory after you are done using it
Title: Re: HeapAlloc pointer usage question
Post by: qWord on April 09, 2012, 12:22:23 AM
You have filled pMem with a pointer to the allocated data block. If you want to access the elements, this pointer must be loaded into a register:
e.g.:
mov esi,pMem
movzx eax,BYTE ptr [esi]
movzx edx,BYTE ptr [esi+1]
mov [esi],dl
mov [esi+1],al


BTW: do you really want to use HEAP_GENERATE_EXCEPTIONS? - this requires SEH.
Title: Re: HeapAlloc pointer usage question
Post by: dedndave on April 09, 2012, 12:29:20 AM
...also
there is probably no need for HeapCreate
each process has a heap already
unless you are playing complex "games" with the heap, just use that

        INVOKE  GetProcessHeap
        mov     hHeap,eax
        INVOKE  HeapAlloc,eax,NULL,<number of bytes>
        mov     hBlock,eax

;hBlock is the address of your memory block
;when you are done using the block, free it...

        INVOKE  HeapFree,hHeap,NULL,hBlock