0

Here is the definition of my function: char*_ft_strdup(const char*s);

I'm trying to reimplement a strdup, but I get stuck with a segfault that occurs at malloc time.

I noticed that it doesn't segfault anymore when I put the pop rdi above malloc, but I don't understand this behavior, any idea?

 .intel_syntax
    
    extern malloc
    extern _ft_strlen
    
    section .text
        global  _ft_strdup
    
    _ft_strdup:
        push    rbp         ; prologue
        mov     rbp, rsp    ; prologue
    
        push    rdi         ; save rdi value (string src)
        call    _ft_strlen  ; compute length of string src
    
        mov     rdi, rax    ; set number of bytes to allocate
        
        call    malloc      ; allocate x bytes
    
        cmp     rax, 0
        je      exit_prog
    
        pop     rdi         ; retrieve string src
        pop     rbp         ; epilogue
        ret
    
    exit_prog:
        xor     rax, rax
        pop     rbp
        ret
Chuck Walbourn
  • 38,259
  • 2
  • 58
  • 81
  • What platform are you targeting? For Windows x64, this doesn't look like it meets the requirements of the full ABI. See [Microsoft Learn](https://learn.microsoft.com/en-us/cpp/build/x64-software-conventions). – Chuck Walbourn May 15 '23 at 18:39
  • 1
    You misalign the stack. You should make sure you adjust `rsp` by multiples of 16. As a simple workaround you can push it twice. PS: note that your `exit_prog` is missing the `pop rdi` – Jester May 15 '23 at 18:39
  • @ChuckWalbourn Im on linux with Intel CPU –  May 15 '23 at 18:41
  • @Jester Do you have any resource to understand this ? –  May 15 '23 at 18:42
  • Sure, the [x86-64 sysv abi documentation](https://www.uclibc.org/docs/psABI-x86_64.pdf), _section 3.2.2 The Stack Frame_ – Jester May 15 '23 at 18:42
  • See [this thread](https://stackoverflow.com/questions/18133812/where-is-the-x86-64-system-v-abi-documented). – Chuck Walbourn May 15 '23 at 18:44
  • I linked as duplicate one of the site's canonical questions on stack alignment. You can find many more by searching the site. – Nate Eldredge May 15 '23 at 19:03
  • Note you have another bug in that the `exit_prog` branch doesn't pop the right number of elements. – Nate Eldredge May 15 '23 at 19:04

0 Answers0