Search code examples
cassemblyx86stackstack-pointer

How to change processor stack?


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;
}

Solution

  • 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.