1

I was writing a program in Nasm and I found out that while winapi functions like CreateProcessA or GetModuleFileNameA do pop their arguments from the stack once they have finished, printf is not doing that.

Is there a reason for that? And more importently: are there any other winapi functions who do not pop the elements from the stack? Because my program is misbehaving and I want to be sure that none of it is caused by not pop'd values.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
MenNotAtWork
  • 145
  • 2
  • 8
  • 2
    Assuming 32-bit code -Because `printf` is not part of the WinApi (which uses STDCALL calling convention where the function cleans up the parameters on the stack). `printf` It is part of the MSVC runttime library, and there the default calling convention is CDECL Basically if you are calling the C library functions or are calling code generated by MSVC/C++ then you wants CDECL calling convention as describe here: https://learn.microsoft.com/en-us/cpp/cpp/cdecl?view=vs-2019 . Additional info is here: https://en.wikipedia.org/wiki/X86_calling_conventions#cdecl – Michael Petch Sep 18 '19 at 23:32

1 Answers1

5

99% percent of exported Windows functions use the stdcall calling convention. On 32-bit x86 this creates smaller more efficient code because the callee restores the stack.

Functions that take a variable number of arguments cannot use stdcall because only the caller knows how many arguments there are and therefore the caller has to restore the stack.

printf is not a Windows function, it is a C library function and most of the C library uses the cdecl calling convention where the caller restores the stack. The Windows provided print functions like wsprintf are also cdecl. You can assume that any API function ending with ... as the final parameter uses cdecl.

Anders
  • 97,548
  • 12
  • 110
  • 164
  • "*You can assume that any API function ending with `...` as the final parameter uses cdecl*" - and you can assume that any Win32 API function uses `stdcall` unless documented otherwise. – Remy Lebeau Sep 19 '19 at 02:32