Question

I'm trying to call 'gets' function of the C library after allocating memory using malloc (also of the C library) and I keep getting segmentation faults and I have no idea why!! I know something is wrong with the stack but I don't know what! here is the code:

section .rodata
LC0:
    DB  "The number is: %i", 10, 0  ;  string

LC1:
    DB  "Allocation failed!!!", 10, 0   ;  string


section .data

section .bss

stack_size:
    RESB    20

section .text
    align 16
    global main
    extern printf
    extern malloc
    extern gets
    link_size EQU 5

_start:
    jmp main 

main:

    mov dword edi, link_size
    push edi
    call malloc
    mov dword [stack_size], eax

    test eax,eax
    jz fail_exit

    add esp,4

    push ecx
    call gets
    pop ecx

    ret

fail_exit:
    push LC1
    call printf
    add esp,4
Was it helpful?

Solution

Putting aside the fact for the moment that gets is a spectacularly unsafe function even when you use it properly (no way to protect against buffer overflow), your immediate problem lies here:

push ecx
call gets
pop ecx

If that ecx is supposed to be the buffer to read the string into, you haven't set it to anything useful. That's almost certainly why you're getting the memory fault.

The buffer returned from malloc was placed into eax, not ecx. I suspect that's what you want to push as the gets parameter.

If the memory you allocated is not where you want to put the characters from gets, you need to initialise ecx to some other buffer before pushing it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top