1

I'm reading "Gray Hat Python". This book teaches debugging techniques in which you can change the variable value through the debugger.

In the code below the author teaches us how to change the counter variable value. But I want to do more, so I add the 'Hello' parameter to the printf function so I can change it into something else like 'Bye'.

What I found through the debugger is that 'Hello' is stored on the Heap. The address in the Heap at which 'Hello' is stored is saved in the Stack; why?

My question is: on what basis are some parameters stored on the stack and some on the heap?

from ctypes import *
import time

msvcrt = cdll.msvcrt
counter = 99999999

while 1:
    msvcrt.printf("Loop iteration %d!\n" , counter, "Hello")
    time.sleep(2)
    counter += 1
Jens Björnhager
  • 5,632
  • 3
  • 27
  • 47
Hybrid
  • 321
  • 3
  • 13
  • 1
    Please Don't Write In Title Case. –  Jul 18 '14 at 12:30
  • Bear in mind that you're handling `'Hello'` differently - what happens if you assign e.g. `word = 'Hello'`, then call `msvcrt.printf(, ..., counter, word)`? – jonrsharpe Jul 18 '14 at 12:34

1 Answers1

2

These things are defined in calling conventions (which is part of an ABI). A calling convention defines a few things, for instance:

  • where (stack or register) and how (in a single cell, spread over multiple cells, reference to heap) to store arguments,
  • the order (left-to-right or right-to-left) in which to store parameters,
  • who is responsible for cleaning up the stack after the call (caller or callee),
  • which registers should be preserved.

Over the years, a bunch of slightly different calling conventions have been used for 32-bit x86 processors (with names like cdecl, stdcall, and fastcall). For 64-bit x86 processors, there are essentially only two calling conventions (one is used by Microsoft, one is used by everyone else on the planet).

On 32-bit Windows, printf uses the cdecl convention. On 64-bit Windows, printf uses the calling convention from Microsoft's 64-bit ABI.

Much more information about calling conventions can be found in this answer.

Community
  • 1
  • 1
  • in this context You Know Why Only `'Hello'` Stored on Heap and Why Not `'Counter'` Stored on Heap – Hybrid Jul 18 '14 at 13:00
  • 1) What do you mean? 2) Why are you still Writing In Title Case? –  Jul 18 '14 at 13:15
  • i mean What is The Difference between `'Hello'` and `'Counter'` That conclude that `'Counter'` should be stored on stack and `'Hello'` should be stored on Heap? – Hybrid Jul 18 '14 at 13:37
  • `'Counter'` is a string, and will therefore *never* be stored on the stack. As far as I know, a reference to the string (an address where the string can be found) is put on the stack. –  Jul 18 '14 at 13:40