0

I need help with my MASM code. When I'm using dynamic allocation for arrays my other variables change values after adding few elements to array.

.686 
.387
.model flat, stdcall 
.xmm

include include\kernel32.inc
includelib lib\kernel32.lib

.data

szyfr DB 9, 15, 19, 2
;tab DD 4 dup (?)   - it works fine
;wynik DD 4 dup (?)   - it works fine

tmp DD 0
j DD 0
t DD 0
x DD 2
tmpa DD 0
tmpb DD 0
dlText DD 0
tab DD ?
wynik DD ?

.code
invoke GetProcessHeap
mov ebx, eax
INVOKE HeapAlloc, ebx, 0,  4      - it doesn't work
mov tab, eax
INVOKE HeapAlloc, ebx, 0,  4      - it doesn't work
mov wynik, eax

Writing to array:

xor edx, edx                
mov eax, esi                    ; esi = iterator = i        
mul x                           ; x = 2
mov edx, eax            
add edx, j                  
add edx, offset tab         
mov eax, t                      ; t = number <0, 26>
mov dword ptr [edx], eax        ; tab[i][j] = number <0, 26>
Welcor
  • 2,431
  • 21
  • 32
Asker
  • 93
  • 7
  • You haven't shown us how you actually write anything to the memory you allocated. – Michael Jan 23 '15 at 15:17
  • By the way, `DD 4 dup(?)` reserves space for 4 DWORDs. `HeapAlloc,ebx,0,4` allocates 4 _bytes_, i.e. _one_ DWORD. – Michael Jan 23 '15 at 15:19
  • @Michael Updated my question, I have tried with HeapAlloc,ebx,0, 100 or even bigger, but it changes nothing. – Asker Jan 23 '15 at 16:09

1 Answers1

2

Your method of accessing the memory you've allocated with HeapAlloc is incorrect. When you do add edx, offset tab you don't get the address of the memory you allocated; you get the address of tab, and tab is just a DWORD. To add the address of your allocated memory you should use add edx,tab.


By the way, these lines:

xor edx, edx                
mov eax, esi                    ; esi = iterator = i        
mul x                           ; x = 2
mov edx, eax  

could be simplified into just:

lea edx,[esi*2]
Michael
  • 57,169
  • 9
  • 80
  • 125