Member method of NULL pointer

Oct 5, 2011 at 6:28am
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 Oct 5, 2011 at 6:29am
Oct 5, 2011 at 6:36am
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).
Oct 5, 2011 at 7:38am
Hi hamsterman,
Thanks. The program will not crash even if we use class instead of struct.. Does your explaination still apply?
Oct 5, 2011 at 9:49am
And may I know I can learn about these tips?
Oct 5, 2011 at 1:16pm
In C++ structs and classes are identical, except for default access modifier.
What tips are you talking about?
Oct 5, 2011 at 1:37pm
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 Oct 5, 2011 at 1:37pm
Oct 5, 2011 at 3:54pm
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();
}
Oct 6, 2011 at 1:57am
Thanks hamsterman, I meant where I can learn about things like the compiler would refactor struct method into a separate function.
Oct 6, 2011 at 7:09pm
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.
Oct 7, 2011 at 1:44am
Great, thanks hamsterman.
Oct 7, 2011 at 2:24am
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.
Oct 10, 2011 at 6:26am
Thanks darkesfriengt.
Oct 10, 2011 at 2:07pm
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.