0

I am using SASM. The x86-asm program may save the first to n-th Fibonacci-Number into an array (eg. n:5 -> [1,2,3,5,8]). The actual algorithm works, but it doesn't save the output from the EAX register into the array, I keep getting an Segfault error:

%include "io.inc"
section.data
size:  DD 5
array: DD 0,0,0,0,0 
section .text
global CMAIN
CMAIN:
mov ebp, esp; for correct debugging    
   MOV eax, 1       ;i
   MOV ebx, 1       ;j
   MOV edx, [size]
   MOV ecx, 0       ; index
   DEC edx          ; max. Index
 fib:
    CMP ecx, edx
    JE end
           MOV edx, ebx             ; safe j     
           MOV ebx, eax             ; j <- i
           ADD eax, edx             ; i <- j+i (with j from edx)
           MOV [array+ecx*4],eax    ; Program received signal SIGSEGV, Segmentation fault.
           INC ecx
           JMP fib
end:
    ret

When implemented without an array, just with the results in EAX, it works:

%include "io.inc"
section .text
global CMAIN
CMAIN:
mov ebp, esp; for correct debugging

MOV eax,1 ; i
MOV ebx,1 ; j
MOV ecx,0 ; n: index

 fib:
    CMP ecx, 4
    JE end
           MOV edx, ebx     ; safe j     
           MOV ebx, eax     ; j <- i
           ADD eax, edx     ; i <- j+i (with j from edx)
           INC ecx
           JMP fib
end:
    ret

I am using SASM with the following build setting:SASM build settings

HeapUnderStop
  • 378
  • 1
  • 9
  • 1
    You are missing a `mov ecx, 0` (or the better version: `xor ecx, ecx`) in the first snippet. A debugger will help you spot this mistakes. – Margaret Bloom Mar 11 '23 at 14:41
  • Thanks @MargaretBloom ,that's a copy/paste error. But it is not the reason for the error. – HeapUnderStop Mar 11 '23 at 14:48
  • 2
    `section.data` should probably be `section .data` – ecm Mar 11 '23 at 14:50
  • 3
    As ecm pointed out: you are also missing a space between `section` and `.data`. NASM should emit a warning. Don't ignore warnings. Of course, since you are clobbering `edx`, the loop won't work but the store won't fault. – Margaret Bloom Mar 11 '23 at 15:02
  • @MargaretBloom , yes that's it. I can't safe j in `edx` since there is the max. Index. I didn't know about the difference between `section.data` and `section .data` Thank you very much! – HeapUnderStop Mar 11 '23 at 15:15
  • [Assembly Language (x86): How to create a loop to calculate Fibonacci sequence](https://stackoverflow.com/a/32661389) has working code to fill an array with the Fibonacci sequence. – Peter Cordes Mar 12 '23 at 03:52

0 Answers0