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

  • your vcs sucks

    I've been hacking on some Haskell stuff lately that's all managed in darcs and it's reminded me of an observation I made over two years ago now (see…

  • jaunty upgrade

    Upgraded to Ubuntu Jaunty. X hung with garbage on the screen after rebooting. Booted into "restore mode" (I forget the exact name), it gave me a…

  • ubuntu summit

    There's an Ubuntu summit going on in Mountain View next week. I'll be there Monday and plan to meet up with someone who's interested in packaging…

  • 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

  • your vcs sucks

    I've been hacking on some Haskell stuff lately that's all managed in darcs and it's reminded me of an observation I made over two years ago now (see…

  • jaunty upgrade

    Upgraded to Ubuntu Jaunty. X hung with garbage on the screen after rebooting. Booted into "restore mode" (I forget the exact name), it gave me a…

  • ubuntu summit

    There's an Ubuntu summit going on in Mountain View next week. I'll be there Monday and plan to meet up with someone who's interested in packaging…