0

I am trying to accept inputs in a dynamically allocated int array but it gives a segmentation fault.

I checked the address returned by calloc. It is valid.
Also I used scanf to accept the value of size of the array and it worked fine.

.text
int_str:       .asciz "%d"

.global main
main:
    pushq %rbp
    movq %rsp, %rbp
    subq $16, %rsp

    /* accept the value of data here
     * this one works fine
     */

    /* allocate memory */
    movq $4, %rdi
    movslq -4(%rbp), %rsi 
    call calloc@plt
    movq %rax, -12(%rbp)

    /* for loop starts here */

    movq $0, %r15
start_loop_1:
    cmpl -4(%rbp), %r15d
    jnl end_loop_1

    leaq int_str(%rip), %rdi
    movq -12(%rbp), %rsi
    leaq (%rsi, %r15, 4), %rsi
    pushq %r15
    xorl %eax, %eax
    call scanf@plt             // <========= gives SIGSEGV here
    popq %r15

    incq %r15
    jmp start_loop_1
end_loop_1:



    movq -12(%rbp), %rdi
    call free@plt

    addq $16, %rsp
    popq %rbp
    ret

  • Probably [glibc scanf Segmentation faults when called from a function that doesn't align RSP](https://stackoverflow.com/q/51070716) - I think your pointer is valid so that just leaves stack alignment. (Or you ran it from `_start` in a static executable without initializing glibc or something.) You didn't show your function prologue so I can't track RSP modifications. BTW, you can keep a pointer in a call-preserved register across scanf calls instead of reloading from the stack. If it's not a duplicate, then it's not a [mcve]. – Peter Cordes Mar 14 '20 at 21:33
  • @Peter Cordes I've done that. The whole code is a bit long, so I just showed the part where the error occurs. – Akarsh Shrivastava Mar 14 '20 at 21:37
  • Yup, stack is aligned on the `call calloc`, but you do one more push before scanf, misaligning the stack. (for no apparent reason; R15 is call-preserved like RBP and RSP. So actually you're destroying `main`'s parent's R15 value because you don't save/restore it.) – Peter Cordes Mar 14 '20 at 23:07

0 Answers0