Isn't dereferencing NULL UB?

C

cjlug

Is the following snippet generating UB, or not?
Strangely, it works fine on MS2008.

#include <iostream>

using namespace std;

class A
{
public:
void print() { cout << "A::print()" << endl; }
}

int main()
{
A *a = NULL;
a->print();
}

A friend of mine said that A::print() isn't depending on A since it's
not virtual and it's not accessing members of A, so it's 'sort of'
static, in terms that it has a known address and can be accessed
without having an instance of an object, like statics.

What's the entire true?
 
B

Balog Pal

cjlug said:
Is the following snippet generating UB, or not?
Yes.

Strangely, it works fine on MS2008.

What strange is there? UB means anything can happen including whatever you
actually see.
void print() { cout << "A::print()" << endl; }
A *a = NULL;
a->print();

-> means (*a).print(). Dereferencing a null pointer is said UB in the
standard text, even explicitly.
A friend of mine said that A::print() isn't depending on A since it's
not virtual and it's not accessing members of A, so it's 'sort of'
static, in terms that it has a known address and can be accessed
without having an instance of an object, like statics.

Indeed, that's the reason is looks like working. On usual architectures
there is no strict need to insert any code that actually dereferences the
pointer masking the bug for the time being.

Just don't do that. If the function needs no access to members make it
static and move on.
 
P

Paul N

Is the following snippet generating UB, or not?
Strangely, it works fine on MS2008.

"My computer could do absolutely anything. But it did something else.
Why is that?"

"Undefined behaviour" simply means that the Standard doesn't specify
what the computer must do. Anything could happen - including it
working exactly the way you expect. Balog Pal has explained why it
might work "properly" on your particular system.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,999
Messages
2,570,246
Members
46,840
Latest member
BrendanG78

Latest Threads

Top