Assembly Code keep showing segment fault

2019-09-01 16:55发布

问题:

Why this assembly code assemble and link fine but show segment fault in runtime. Commented after the instruction to give a idea what I wanted to do.

  jmp short init

action:
  pop esi
  xor eax, eax
  mov byte [esi+24], al ;null terminating the string.
  mov dword [esi+25],24 ;length of the string

  mov al,4 ;syscall write
  mov ebx,1 ;standard out
  lea ecx,[esi]   ;<<---------- Unsure about this. probably load the address of the string to ecx  
  mov edx,[esi+25] ;<<-- load edx with string length
  int 80h


init:
  call action
  db "what a pity! not working#LLLL"

I am using NASM to assemble and ld to link. This program will run on a 64-bit machine but I want it to be 32-bit compatible.

回答1:

You want to have the address of the string in ecx. So why do you pop esi ? Use pop ecx and you already have it in the correct register. You don't need it anyway for some other purpose.

Apart from that, you are writing to the code segment, which is not writable by default.