Author Topic: Segmentation Issue  (Read 7219 times)

Offline Sharlenehargrove

  • Jr. Member
  • *
  • Posts: 7
Segmentation Issue
« on: February 07, 2023, 10:31:24 AM »
Hi,

I'm a student in computer science and I have to create a small program in assembly. This program must then be used in a C++ program.
Now onto the purpose : it must take a destination vector, a source vector and the length of thoses vectors (which is the same), take every number in the first vector, multiply it by two and then put it in the second vector.

My problem is this, for the core of the program, it looks like this :
    xor edi, edi ; initialising edi at 0 for the offset
table_multiplier:   
    mov esi, [edx + edi*4] ; getting the value from the source table
    shl esi, 1 ; multiplying the taken value by 2
    mov [eax + edi*4], esi ; putting the value in the destination table
    inc edi
    loopnz table_multiplier

ecx contains the length of the vector. When I run it in sasm, I don't have any problem. But when I try using it in my C++ code, I get a segmentation fault. I've been trying to wrap my head around this for a day now and I can't seem to find the problem. YourTexasBenefits.com Login
« Last Edit: February 08, 2023, 04:59:20 AM by Sharlenehargrove »

Offline fredericopissarra

  • Full Member
  • **
  • Posts: 373
  • Country: br
Re: Segmentation Issue
« Reply #1 on: February 07, 2023, 10:49:53 AM »
To what environment? Windows? Linux?
Let's say it is Linux x86-64 (make sobre adaptions if your environment is i386):
Code: [Select]
  bits  64
  default rel

  section .text

  global memcpy_dbl

; Entry: RDI = destination array ptr
;        RSI = source array ptr
;        EDX = # of int elements
memcpy_dbl:
  jmp   .test

  align 4
.loop:
  lodsd
  add   eax,eax
  stosd

  sub   edx,4
.test:
  test  edx,edx   ; are there elements to double?
  jnz   .loop       ; yes, do it.

  ret
« Last Edit: February 07, 2023, 12:08:26 PM by fredericopissarra »

Offline fredericopissarra

  • Full Member
  • **
  • Posts: 373
  • Country: br
Re: Segmentation Issue
« Reply #2 on: February 07, 2023, 12:08:02 PM »
For i386 mode (Windows and Linux):
Code: [Select]
  bits  32

; _memcpy_dbl stack frame.
struc mcdstk
          resd  2   ; old esi and edi
          resd  1   ; return address.

          ; arguments
destptr:  resd  1
srcptr:   resd  1
elems:    resd  1
endstruc

  section .text

  global _memcpy_dbl

; Assumes FLAT address mapping (DS=ES).
_memcpy_dbl:
  ; esi and edi must be preserved.
  push  esi
  push  edi

  mov   esi,[esp + mcdstk.srcptr]
  mov   edi,[esp + mcdstk.destptr]
  mov   ecx,[esp + mcdstk.elems]

  jmp   .test

  align 4
.loop:
  lodsb
  add   eax,eax
  stosb

  sub   ecx,4

.text:
  test  ecx,ecx
  jne   .loop

  pop   edi
  pop   esi
  ret