Evan Martin (evan) wrote in evan_tech,
Evan Martin
evan
evan_tech

do my research / C++ black magic

I have a C/architecture question for y'all.

As of today I'm going to start on some work on Cyclone. (Here's the manual, if you're curious.)

Apparently the C standard doesn't require all pointer types to be interchangable-- that is to say, you can't cast from int* to char* and back and be guaranteed you're ok. void* is instead used as the "superpointer" type, where you can cast anything to void* and back and be ok, and that's why you make generic data types work with void*s.

So my question is: can you name a system where the difference between pointer types actually exists? How about function pointers? Are they also always the same size? (For example, you could imagine a system where code and data were somehow represented by differently-sized pointers-- does such a system exist?)

Speaking of varying-sized pointers, here's some more wacko code, this time in C++.

#include <stdio.h>

class C {
public:
  virtual void f(void) { }
};

class D : public C {
public:
  virtual void f(void) {
    printf("i am a D!\n");
  }
};

void main(void) {
  printf("%d\n", sizeof(&C::f));

  void (C::*ourptr)() = &C::f;

  D* d = new D;
  C *creallyd = d;
  (creallyd->*ourptr)();
}

(First, isn't C++ function pointer syntax even uglier than C? Man, that's some ugly-looking syntax.)

But the bonus question: What does this print?

If you know that first printf prints 8, not 4, you'll probably be able to figure out that ourptr somehow magically carries around information about vtable of C and manages to actually call the printing version of D.

Thankfully, Cyclone only deals with C, so I don't have to worry about that. :)
Subscribe

  • inspiration

    _why: "when you don't create things, you become defined by your tastes rather than ability. your tastes only narrow & exclude people. so create."

  • exceptions

    This bug makes me a little sad. From one of the patches for fixing: - @string = (str.string rescue str) + @string = str.respond_to?(:string) ?…

  • minimal openid consumer

    Here's a minimal OpenID consumer using the Ruby OpenID libraries. (Their included examples only contain Rails spew.) This example is useful for…

  • Post a new comment

    Error

    default userpic
    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 23 comments

  • inspiration

    _why: "when you don't create things, you become defined by your tastes rather than ability. your tastes only narrow & exclude people. so create."

  • exceptions

    This bug makes me a little sad. From one of the patches for fixing: - @string = (str.string rescue str) + @string = str.respond_to?(:string) ?…

  • minimal openid consumer

    Here's a minimal OpenID consumer using the Ruby OpenID libraries. (Their included examples only contain Rails spew.) This example is useful for…