gpt4 book ai didi

c - 从 C 代码调用汇编函数时出现段错误

转载 作者:行者123 更新时间:2023-11-30 15:08:05 24 4
gpt4 key购买 nike

我正在尝试将汇编函数链接到 C 代码以进行练习。这是我的汇编函数,用 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

它基本上定义了一个函数,用于查找数组的最大数量(或应该是)

还有我的 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));
}

我用gcc -o max max.s max.c编译它们。
执行代码时出现 SegmentationFault
我怀疑我没有以正确的方式访问该值,但我不明白为什么,即使我的代码基于打印 argcargv< 的示例代码 从命令行调用时的值。

我正在运行 Debian 8 64 位

最佳答案

问题是:

  • 不保留 %ebx%edi
  • 未编译 32 位(必须为 gcc 使用 -m32 标志)
  • cmpl 操作数已反转

谢谢大家,问题已经解决了。我将更多地关注调试工具(逐步反汇编和运行非常有用)!

关于c - 从 C 代码调用汇编函数时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37681488/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com