NASM x86_64 scanf分段故障 [英] NASM x86_64 scanf segmentation fault

查看:93
本文介绍了NASM x86_64 scanf分段故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是nasm的新手,我真的很想学习如何通过用户输入来存储数字.使用scanf时,我无法摆脱出现分段错误的问题.我已经在网上搜索了,但是还没有找到解决此问题的任何方法. 我尝试了代码,但它对我不起作用.

I am new to nasm and I really want to learn how to store a number with user input. I can't get rid of getting segmentation fault when using scanf. I have searched the web, but havent found any solution to this problem. I tried this code but it doesn't work for me.

有人可以向我解释我在做什么错吗?

Can someone explain me what am I doing wrong?

global main

extern printf, scanf

section .data
   msg: db "Enter a number: ",10,0
   format:db "%d",0

section .bss
   number resb 4

section .text
main:
   mov rdi, msg
   mov al, 0
   call printf

   push number
   push format
   call scanf
   ret

提前谢谢!

推荐答案

x86-64调用惯例通常不会推论据.此外,您还必须告诉一个具有可变数量的参数的函数,以及您提供了多少个浮点参数.

The x86-64 calling convention doesn't push the arguments generally. Additionally you have to tell a function with variable count of arguments, how many floating point arguments you provide.

这有效:

global main
extern printf, scanf

section .data
   msg: db "Enter a number: ",10,0
   format:db "%d",0

section .bss
   number resb 4

section .text
main:
   sub  rsp, 8       ; align the stack to a 16B boundary before function calls

   mov rdi, msg
   mov al, 0
   call printf

   mov rsi, number
   mov rdi, format
   mov al, 0
   call scanf

   add   rsp, 8      ; restore the stack
   ret

顺便说一句:如果要使用浮点数,则必须在调用该函数之前将堆栈对齐到16个字节的边界.

BTW: If you want to work with floating point numbers, you have to align the stack to a 16 byte boundary before calling the function.

这篇关于NASM x86_64 scanf分段故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆