下面是一个x86汇编程序,旨在由NASM在64位CentOS下组装,通过一个没有gdb
的远程终端,也不允许安装它。
主.cpp
#include <stdio.h>
extern "C" void looping_test();
int main(void)
{
looping_test();
return 0;
}
func.asm
extern printf
section .data
hello: db 'Hello World!', 20
helloLen: equ $-hello
section .text
global looping_test
looping_test: ; print "Hello World" 5 times
mov ecx, 0; initialize the counter
while_loop_lt:
push hello
call printf
inc ecx
cmp ecx, 4; This is exit control loop.
je end_while_loop_lt
end_while_loop_lt:
ret
生成文件
CC = g++
ASMBIN = nasm
all : asm cc link
asm :
$(ASMBIN) -o func.o -f elf -g -l func.lst func.asm
cc :
$(CC) -m32 -c -g -O0 main.cpp &> errors.txt
link :
$(CC) -m32 -g -o test main.o func.o
clean :
rm *.o
rm test
rm errors.txt
rm func.lst
输出:
[me@my_remote_server basic-assm]$ make
nasm -o func.o -f elf -g -l func.lst func.asm
g++ -m32 -c -g -O0 main.cpp &> errors.txt
g++ -m32 -g -o test main.o func.o
[me@my_remote_server basic-assm]$ ./test
Segmentation fault
[me@my_remote_server basic-assm]$
为什么我的程序给我一个分段错误?
我已经根据@MichaelPetch和@PeterCordes的评论进行了修改,并从以下源代码中获得了所需的输出:
func.asm
extern printf
section .data
hello: db "Hello World!", 20
helloLen: equ $-hello
section .text
global looping_test
looping_test: ; print "Hello World" 5 times
mov ebx, 0 ; initialize the counter
while_loop_lt:
push hello
call printf
add esp, 4
inc ebx
cmp ebx, 5 ; This is exit control loop.
je end_while_loop_lt
jmp while_loop_lt
end_while_loop_lt:
ret