分段故障组装调试

时间:2018-07-13 05:40:07

标签: assembly segmentation-fault nasm

以下代码有错误,可能会导致分段错误。描述问题。为什么会出现段错误?解决办法是什么?

  main: 
   call do_stuff 
   ret
  do_stuff: 
  push ebp 
  mov ebp, esp

  mov eax, 10 
  mov ebx, 20 
  mov ecx, 30 
  mov edx, 40 
  mov ebp, 50

  add eax, ebx 
  add eax, ecx 
  add eax, edx 
  add eax, ebp

  mov esp, ebp 
  pop ebp re

1 个答案:

答案 0 :(得分:0)

问题是堆栈处理。首先将堆栈指针(esp)的地址写入帧指针(ebp),然后更改ebp并将其移回esp,这将导致程序崩溃。您的代码应重写如下:

do_stuff: 
  push ebp 
  mov ebp, esp ; for correct debugging

  mov eax, 10 

  add eax, 20 
  add eax, 30 
  add eax, 40 
  add eax, 50

  mov esp, ebp ; refresh stack pointer if it was changed
  pop ebp ; get pointer to previous frame
  ret ; the result will be stored in eax