我不明白如何将字符串转换为整数。
这是家庭作业,但是我不想要问题的答案——(又名正确代码)。如果有人能解释我做错了什么,我将不胜感激! :(
提前致谢!!!
我在 32 位虚拟机上运行 Ubuntu 12.04。
我编译:
nasm -f elf proj2.asm
我链接到:
gcc -o proj2 proj2.o
然后运行它:
./proj2
它显示第一个数字,但当我尝试使用 atoi
时,它会给我一个段错误。
我有一位老师希望我们:
从这样排列的文本文件中读取数字:
4 5 4 2 9
(每个整数前有空格)
按照他的指示:“务必将七 (7) 个字符读入缓冲区以获取整行。这五个字符代表数字以及字符 CR 和 LF。CR 是带十六进制的回车符代码 0x0D
和 LF 是十六进制代码 0x0A
的换行字符。")
我已经删除了文件中的空格,并尝试以这种方式读取它,但没有帮助。
整数将被读取到堆栈上的数组中,最大整数数为 250。但这不是问题:/
到目前为止,下面是我的代码。
BUFFERSIZE equ 10
section .data
file_name: db "/home/r/Documents/CS/project2/source/indata.txt", 0x00
file_mode: db "r", 0x00
output: db "%i",0xa
test: db "hello world",10
format: db "%u"
numToRead: db 1
temp: db "hi"
num:db "1",0,0
section .bss
fd: resd 4
length: resd 4
buffer resb BUFFERSIZE
;i was trying to use buffers and just
;read through each character in the string,
;but i couldn't get it to work
section .text
extern fopen
extern atoi
extern printf
extern fscanf
extern fgets
extern getc
extern fclose
global main
main:
;setting up stack frame
push ebp
mov ebp, esp
;opens file, store FD to eax
push file_mode
push file_name
call fopen
;save FD from eax into fd
push eax
mov ebx,eax
mov [fd],ebx
;ebx holds the file descriptor
;push in reverse order
push ebx
push numToRead
push temp
call fgets
push eax
call printf ;prints length (this works, i get a 4.
;Changing the number in the file changes the number displayed.
;I can also read in several lines, just can't get any ints!
;(So i can't do any comparisons or loops :/ )
;i shouldn't need to push eax here, right?
;It's already at the top of the stack from the printf
;pop eax
;push eax
call atoi
;calling atoi gives me a segmentation fault error
push eax
call printf
mov esp,ebp
pop ebp
ret
编辑: 有趣的是,我可以很好地调用 atoi。就在我尝试的时候
push eax
call atoi
push eax
call printf
我遇到段错误。
最佳答案
除非我在我的手机上看不到它,但你在通话后没有平衡堆栈。这些 c 函数不是 stdcall,因此您必须在每次调用后调整堆栈。我这样做:
添加 esp, 4 * numofpushes
这可能是您的段错误的来源。
关于linux - x86 NASM Linux 程序集中的 ATOI 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15484661/