0

What is the output of the following code? Suppose that necessary headers have been included.

Does this lead to undefined behavior? When compiled with g++ and run, it prints "test".

class A {
public:
    void test()
    {
        printf("test\n");
    }
};

int main()
{
    A *pa = NULL;
    pa->test();
}
DrizzleX
  • 377
  • 3
  • 11
  • `When compiled with g++ and run, it prints "test"` UB doesn't mean it always crash. Actually it may and will work on many platforms. But it's UB anyway. – Matt Mar 23 '16 at 15:23

1 Answers1

3

Any dereference of a NULL pointer is undefined behavior. Thus your example exhibits undefined behavior too.

owacoder
  • 4,815
  • 20
  • 47
  • I guess it works in the given environment because `test` does not access a data member of an instance... – Codor Mar 23 '16 at 15:18
  • 2
    That may be. But speculation as to why it works in said environment doesn't really help with production coding, because this example should never be used in actual code. – owacoder Mar 23 '16 at 15:19
  • No, you are totally right. I was just wondering. – Codor Mar 23 '16 at 15:20
  • @Codor `does not access a data member` change `test()` to `virtual` and it will crash too. – Matt Mar 23 '16 at 15:21
  • @owacoder, well, as a matter of fact, knowing how particular UB exhibits itself on your target platform is **invaluable** tool. It just used in the opposite direction - 'my program crashed yesterday after upgrade in B::foo(), but didn't crash before' - analyze the change - see that foo() started accessing members when it didn't before - conclude it was called with the bad pointer - fix the issue. – SergeyA Mar 23 '16 at 15:27