我在 ASM 中的 strdup

My strdup in ASM

大家好我学校的每个人我必须在 ASM [intel] 中做我自己的 strdup 函数 [NASM].

我有一个奇怪的问题...

在我的代码中,如果我 call _malloc

我的代码出现此错误的段错误:

Program received signal SIGSEGV, Segmentation fault.
0x00007fff849612da in stack_not_16_byte_aligned_error () from /usr/lib/system/libdyld.dylib

我不明白为什么,因为在 .text 部分我说 extern _malloc

有人知道为什么我会犯这个错误吗? :)

这是我的代码:

section .text
     global _ft_strdup
     extern _strlen
     extern _malloc
     ;  extern _ft_memcpy

_ft_strdup:
     call _strlen           ;rax = len of str
     mov r8, rdi            ;r8 = str = src
     inc rax                ;rax++
     ;  mov r9, rax         ;len of dest with '[=11=]'
     mov rdi, rax           ;to send the len for malloc
     call _malloc           ;rax = ptr of dest
     ;  cmp rax, 0          ;malloc failled
     ;  jle _error_malloc
     ;  mov rdi, rax        ;malloc param 1 of ft_memcpy
     ;  mov rsi, r8         ;str in param 2 of ft_memcpy
     ;  mov rdx, r9         ;len of str with '[=11=]' param 3 of ft_memcpy
     ;  call _ft_memcpy     ;call ft_memcpy
     ret
_error_malloc:
     xor rax, rax           ;return NULL
     ret

所有以ft_开头的函数都与libc Thx all

相同

此错误消息表明您调用 malloc 时堆栈未充分对齐。 amd64 的 SysV-ABI 要求堆栈在函数调用时对齐到 16 字节。

在您自己的代码中,您可以通过确保始终将偶数个四字压入堆栈来确保这一点,并记住在入口时,堆栈由于 return 而错位 8 个字节地址已经在堆栈上。

没有看到您的源代码,很难提供更具体的帮助。