1

I need to receive input from user and I am required to use malloc to init the buffer first. I can't find any example online.

This is the buffer:

 section .bss
        buffer:
                resb 80                     ;store my input

How is it done? Is this ok? (it compiles but I don't think it works...)

    push 80
    push buffer
    call malloc
    add esp, 8 

or maybe this? (this doesn't compile)

push 80
push buffer
call malloc
add esp, 8 
mov buffer, [eax]

The thing is that when I give the buffer the input 0, it prints 2608 instead of 48 as the ASCII value should print.

Input 1 -> gives 2609 accordingly. So my guess is that somehow the buffer has values it's not supposed to have.

This is the fgets part (it works ok)

 push dword [stdin]             ;fgets need 3 param
    push dword 80                   ;max lenght
    push dword buffer               ;input buffer
    call fgets
    add esp, 12                     ;remove 3 push from stuck

and this is the print part:

push dword [buffer]             ;push string to stuck
push INT_FORMAT                     ; its INT_FORMAT:DB "%d", 10, 0
call printf             
add esp, 8              ;remove pushed argument
Julian
  • 9,299
  • 5
  • 48
  • 65
lolu
  • 370
  • 4
  • 20
  • 2
    `malloc` only takes one argument: the number of bytes to allocate. SO you do not want to push the `buffer` as an argument. The pointer to the allocated buffer is returned by the function, so will be in `eax` upon return. You don't need `buffer` reserving 80 bytes since you're dynamically allocating 80 bytes. – lurker May 14 '15 at 16:40

1 Answers1

3

malloc has one DWORD parameter, which is the size in bytes to allocate, so it should be called:

push <size>
call malloc
add esp, 4
; now eax points to an allocated buffer of the requested size
mov [eax], ebx ; will set the first 4 bytes of the buffer to ebx (etc...)
Mark Segal
  • 5,427
  • 4
  • 31
  • 69