I write the code to computer each character in a string's frequency, and the array is index is from 0 to 255, which are ascii index and the value is the frequency that the character appear.
I compare each character in the string and add it 1 in the array each time.
But I cannot find the error that the count seem to be not right(too large)?
The result should be
but my result's count is too large.
The error comes in the L1 loop and I don't know why the loop will cause very large number.
Please give me some guidance that what I do wrong.
Thank for your reading.
INCLUDE Irvine32.inc
.data
testString BYTE "AAEBDCFBBC",0
freqTable DWORD 256 DUP(0)
prompt BYTE 0Dh, 0Ah, 0
prompt1 BYTE ": ", 0
.code
Freq PROC uses edi,
tString:PTR BYTE,
fTable:PTR DWORD
mov eax,0
CLD
mov edi,fTable
mov ecx,256
rep stosd;initialize fTable 0
mov edi,fTable;reset edi position
mov edx,tString
mov ecx,SIZEOF tString;element number
dec ecx;remove null character
L1:
mov al,[edx] ;character value
inc edx ;index ++
inc dword ptr[edi+eax] ;value ++
Loop L1
ret
Freq ENDP
main PROC
main ENDP
INVOKE Freq, ADDR testString, ADDR freqTable
mov ecx, 256
mov ebx, 0
mov edi,OFFSET freqTable
mov eax, 0
L1:
call WriteHex;index
mov edx,OFFSET prompt1
call WriteString;": "
mov ebx, [edi + eax]
xchg eax,ebx
call WriteInt
xchg eax,ebx
mov edx,OFFSET prompt
call WriteString;endline
inc eax;index ++
Loop L1
;ret
END main
From a first glance your code seems about right. I find the line mov ecx,SIZEOF tString
a little suspicious, make sure that returns the size of your string - I fear it just returns the size of the pointer. (But that should make the count less not more.)
Also, during the write loop, make sure that the various functions you call don't change any registers you depend on, particularly eax
is in danger.
Otherwise you should use a debugger to check whether the produced result is correct so you can tell whether it's the Freq
function or your printing loop that's faulty. Having found that, you should step through that part to see where it goes wrong.
Update
Your freqTable
is apparently made up of dwords (4 bytes each) but your indexing uses 1-byte units. You'll have to change inc dword ptr[edi+eax]
into inc dword ptr[edi+eax*4]
in the counting loop, and similarly the mov ebx, [edi + eax]
into mov ebx, [edi + eax*4]
in the printing loop.