调用sprintf在程序集中崩溃

时间:2014-05-04 23:30:02

标签: assembly x86 fasm

我试图调用sprintf来格式化字符串并将结果存储在堆栈变量中。但是,我的尝试失败了,它立即崩溃了。

sub esp, 0x100                                  ;Allocate 256 bytes on the stack.
push dword[RequestedFile]                       ;push string2
push dword[Host]                                ;push string1
push dword[GetHeader]                           ;push format   "String1: %s, String2: %s"
push dword[ebp - 0x04]                          ;push buffer/stack variable
call [sprintf]                                  ;store string in buffer
add esp, 0x10                                   ;restore stack

push dword[ebp - 0x04]                          ;push the stack variable.
push StringFormat                               ;push the format
call [printf]                                   ;print the new string.
add esp, 0x08                                   ;restore the stack

add esp, 0x100                                  ;destroy the stack variable.

任何想法我做错了什么?

1 个答案:

答案 0 :(得分:2)

您正在使用[ebp-4],就好像它是指向缓冲区的指针一样,实际上它只是缓冲区最后4个字节中的随机内存垃圾(假设还没有从堆栈中分配任何其他东西) 。如果您想继续使用[ebp-4],您还需要从堆栈中分配它并将其初始化为地址。例如:

sub esp, 0x104                  ;Allocate 256 bytes buffer and 4 bytes pointer
mov dword[ebp - 0x04], esp      ;store address of buffer in local variable
push dword[RequestedFile]       ;push string2
push dword[Host]                ;push string1
push dword[GetHeader]           ;push format   "String1: %s, String2: %s"
push dword[ebp - 0x04]          ;push buffer/stack variable
call [sprintf]                  ;store string in buffer
add esp, 0x10                   ;restore stack

push dword[ebp - 0x04]          ;push the stack variable.
push StringFormat               ;push the format
call [printf]                   ;print the new string.
add esp, 0x08                   ;restore the stack

add esp, 0x104                  ;destroy the stack variables.