2

Why doesn't this code print "test"?

#include <stdio.h>
#include <stdlib.h>

void foo ( void ) {
   printf("test\n");
}

__declspec(naked)
void bar ( void ) {
   asm {
      push 0x000FFFFF
      call malloc
      pop ecx
      push eax
      add eax, 0x000EFFFF

      mov ecx, esp
      mov esp, eax
      push ecx

      call foo

      pop esp
      call free
      pop ecx
      ret
   }
}

int main(int argc, char* argv[])
{
   bar();
   return 0;
}
stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268
Mike
  • 1,760
  • 2
  • 18
  • 33
  • You should probably make that 'printf("test\n");' in case there are buffering issues. – Paul Tomblin May 06 '09 at 18:55
  • Nice challange for me. I did not code in asm for quite some time, had to refresh myself on calling conventions to compile this. – Suma May 06 '09 at 19:15

1 Answers1

10

Because your newly allocated stack is not DWORD aligned. Change code to this:

  push 0x00100000
  call malloc
  pop ecx
  push eax
  add eax, 0x000f0000

... and it will print as needed.

Be sure to add \n to avoid buffering issues as advised by Paul.

Suma
  • 33,181
  • 16
  • 123
  • 191
  • Thank you so much!! The funny or sad thing is that I have been reading an Intel x86 Architecture manual when I got too excited I just had to start coding. The section I stopped on was Stack Align. :) – Mike May 06 '09 at 19:24