[英]Problems with ATOI in x86 NASM Linux assembly
我不明白如何將字符串轉換為整數。
這是家庭作業,但我不想回答這個問題——(AKA 正確代碼)。 如果有人能解釋我做錯了什么,我真的很感激! :(
提前致謝!!!
我在 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,因此您必須在每次調用后調整堆棧。 我願意:
add esp, 4 * numofpushes
這可能是您的段錯誤的根源。
編輯:有趣的是,我可以很好地調用 atoi。 那是我嘗試的時候
push eax
call atoi
push eax
call printf
我得到分段錯誤。
來自atoi 參考: “成功后,該函數將轉換后的整數作為 int 值返回。” .
將任何隨機整數(如4
)作為以下printf
的第一個參數(即format
字符串指針)傳遞不太可能結束。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.