Member method of NULL pointer

Hi all,
Recently my friend found out that the following code wouldn't crash:

1
2
3
4
5
6
7
8
9
10
11
12
struct aStruct
{
  print()
  {
    printf("hahaha\n")
  }
};
int main()
{
   aStruct* p= 0;
   p->print();
}


I guess it is because p has 2 memory parts, 1 is for member functions, the other is for data. The assignment (p=0) only affects the part reserved for data. So by right it still works normally if we access the other part (p->print()).

Am I right or is it the compiler is just so smart that it altered the object?
Last edited on
A struct does not point to it's functions. That code works the same way as
1
2
3
4
5
6
7
8
9
struct aStruct{};
void print( aStruct* ptr ){
    printf("hahaha\n")
}
int main()
{
   aStruct* p= 0;
   print( p );
}


It would crash, however, if print tried to access members of ptr (or this, in your case).
Hi hamsterman,
Thanks. The program will not crash even if we use class instead of struct.. Does your explaination still apply?
And may I know I can learn about these tips?
In C++ structs and classes are identical, except for default access modifier.
What tips are you talking about?
Hi hamsterman,
I have tried both the was , what mancs is descussing about and what you are descussing about . But both seems working with out the crash .
I am not able to get that .. can any one of you explain that ?
Last edited on
They are supposed to work without a crash.

If you want something to crash, try this:
1
2
3
4
5
6
7
8
9
10
11
12
struct aStruct {
  int x;
  void print() {
    x = 5;
    printf("hahaha\n")
  }
};

int main() {
   aStruct* p= 0;
   p->print();
}
Thanks hamsterman, I meant where I can learn about things like the compiler would refactor struct method into a separate function.
I wouldn't call it refactoring. There is just one way to represent a function (sort of. you may want to google "calling conventions"). I only meant that the compiled code is (nearly) the same. The compiler does not transform methods to global functions.

As for learning, I can't say. Just ask here when you see something you don't know. Eventually some things will become apparent. Learning assembly might help some.
Great, thanks hamsterman.
closed account (1yR4jE8b)
Member functions always implicity pass the calling object as the this pointer. The program doesn't crash because you aren't using the this pointer. That's it.
Thanks darkesfriengt.
Note that this might crash or do weird things (if, for example, the function you are trying to call is virtual), so I don't recommend you ever think you can do it. Technically the language prohibits it.
Topic archived. No new replies allowed.