Magic, More Magic

I have solved the riddle of the Magic Rect. What was happening was this:

  • Call to GraphicsPort::newInternalGraphicsPort(Rect clipRect)
  • newInternalGraphicsPort creates new Rect
  • Call to getClientRect()
  • Call to GraphicsPort::newGraphicsPort(Rect* clipRect)
  • newGraphicsPort sets internal _clipRect pointer to the clipRect parameter
  • newGraphicsPort exits
  • newInternalGraphicsPort exits

The problem is that the rect I pass into newInternalGraphicsPort isn’t the rect I pass into newGraphicsPort - the first function call makes a duplicate of the rect as I’m not passing it as a reference/pointer. What I pass into newGraphicsPort is a pointer to the copy. When the two functions exit, the pointer is suddenly pointing at a rect that no longer exists.

I think the two lines inside newInternalGraphicsPort that made the function work (creating a rect and calling getClientRect) moved the stack pointer along just far enough so that when the clipRect got destroyed, the memory was still there long enough for me to work with it.

Sometimes C++ likes to see how far it can push you before you crack.