[英]Segmentation fault when calling assembly function from C code
I'm trying to link assembly functions to a C code for exercise. 我正在尝试将汇编函数链接到C代码以进行练习。 Here's my assembly function, written in x86 assembly: 这是我用x86汇编语言编写的汇编函数:
.code32
.section .text
.globl max_function
.type max_function, @function
# i parametri saranno in ordine inverso a partire da 8(%ebp)
max_function:
pushl %ebp # save ebp
movl %esp, %ebp # new frame function
movl $0, %edi # first index is 0
movl 8(%ebp), %ecx # ecx is loaded with the number of elements
cmpl $0, %ecx # check that the number of elements is not 0
je end_function_err #if it is, exit
movl 12(%ebp),%edx # edx is loaded with the array base
movl (%edx), %eax # first element of the array
start_loop:
incl %edi #increment the index
cmpl %edi,%ecx #if it's at the end quit
je loop_exit
movl (%edx,%edi,4),%ebx #pick the value
cmpl %ebx,%eax #compare with actual maximum value
jle start_loop #less equal -> repeat loop
movl %ebx,%eax #greater -> update value
jmp start_loop #repeat loop
loop_exit:
jmp end_function #finish
end_function: #exit operations
movl %ebp, %esp
popl %ebp
ret
end_function_err:
movl $0xffffffff, %eax #return -1 and quit
jmp end_function
It basically defines a function that finds the maximum number of an array (or it should be) 它基本上定义了一个函数,该函数查找数组的最大数目(或者应该是)
And my C code: 和我的C代码:
#include <stdio.h>
#include <stdlib.h>
extern int max_function(int size, int* values);
int main(){
int values[] = { 4 , 5 , 7 , 3 , 2 , 8 , 5 , 6 } ;
printf("\nMax value is: %d\n",max_function(8,values));
}
I compile them with gcc -o max max.s max.c
. 我用gcc -o max max.s max.c
编译它们。
I get a SegmentationFault
when executing the code. 执行代码时出现SegmentationFault
。
My suspect is that I don't access the value in a right manner, but I can't see why, even because I based my code on an example code that prints argc
and argv
values when called from the command line. 我的怀疑是我没有以正确的方式访问该值,但是我什至看不到原因,即使我将我的代码基于示例代码,该示例代码在从命令行调用时也会打印argc
和argv
值。
I'm running Debian 8 64-bit 我正在运行Debian 8 64位
The problems were: 问题是:
%ebx
and %edi
不保留%ebx
和%edi
-m32
flag for gcc) 无法编译为32位(必须对gcc使用-m32
标志) cmpl
operands were inverted cmpl
操作数被倒置 Thanks everybody, problem is solved. 谢谢大家,问题解决了。 I'll focus more on debugging tools to (disassembling and running step by step was very useful)! 我将重点放在调试工具上(逐步拆卸和运行非常有用)!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.