473,324 Members | 2,179 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

Undefined behaviour with Non-static, non-polymorphic + null pointer?

Hi,

I'm fairly sure this is undefined behaviour, despite the fact that
it compiles and 'runs' (prints "this doesn't exist") on all my platforms:

#include <iostream>

class foo {
public:
void bar() {
std::cout << "hello evil world!" << std::endl;
if (this) {
std::cout << "this exists" << std::endl;
}
else {
std::cout << "this doesn't exist!" << std::endl;
}
}
};

int main() {
foo *inst = 0;
inst->bar();

return 0;
}

Can someone please quote chapter and verse on this one and help me win
my current "this is a very bad idea" argument I'm having? I'd have
expected it to be forbidden under some general rule, and no exceptions
to have been made for it? Or is it actually really legal and defined
because nothing ever dereferences the this pointer?

Thanks,
Alan
Nov 21 '07 #1
11 1514
Alan Woodland wrote:
I'm fairly sure this is undefined behaviour, despite the fact that
it compiles and 'runs' (prints "this doesn't exist") on all my
platforms:

#include <iostream>

class foo {
public:
void bar() {
std::cout << "hello evil world!" << std::endl;
if (this) {
std::cout << "this exists" << std::endl;
}
else {
std::cout << "this doesn't exist!" << std::endl;
}
}
};

int main() {
foo *inst = 0;
inst->bar();
Here you're "using" the pointer that has an invalid value (does not
point to any object). That's undefined behavour. I could not quickly
locate the exact passage in the Standard that says that it is, but I
am sure you can find a mention of it in the archives, just search for
"dereference null pointer".
>
return 0;
}

Can someone please quote chapter and verse on this one and help me win
my current "this is a very bad idea" argument I'm having? I'd have
expected it to be forbidden under some general rule, and no exceptions
to have been made for it? Or is it actually really legal and defined
because nothing ever dereferences the this pointer?
The expression

inst->bar()

is in fact

(*inst).bar()

which already dereferences the null pointer 'inst'.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Nov 21 '07 #2
Victor Bazarov wrote:
Alan Woodland wrote:
>I'm fairly sure this is undefined behaviour, despite the fact that
it compiles and 'runs' (prints "this doesn't exist") on all my
platforms:

#include <iostream>

class foo {
public:
void bar() {
std::cout << "hello evil world!" << std::endl;
if (this) {
std::cout << "this exists" << std::endl;
}
else {
std::cout << "this doesn't exist!" << std::endl;
}
}
};

int main() {
foo *inst = 0;
inst->bar();

Here you're "using" the pointer that has an invalid value (does not
point to any object). That's undefined behavour. I could not quickly
locate the exact passage in the Standard that says that it is, but I
am sure you can find a mention of it in the archives, just search for
"dereference null pointer".
> return 0;
}

Can someone please quote chapter and verse on this one and help me win
my current "this is a very bad idea" argument I'm having? I'd have
expected it to be forbidden under some general rule, and no exceptions
to have been made for it? Or is it actually really legal and defined
because nothing ever dereferences the this pointer?

The expression

inst->bar()

is in fact

(*inst).bar()

which already dereferences the null pointer 'inst'.
Thanks. It's funny, I'd never actually though about the implications of
that in this context before. Just found the following quote which ought
to convince certain people:

The Standard says that "p->" is
converted to "(*p)." (see section 5.2.5) and no matter how you slice it,
*p is a dereference. Dereferencing a null pointer results in undefined
behaviour.

Some compilers may ignore the conversion, but that's part of the
"undefined" part of the behaviour. You cannot rely on it happening on
all compilers - not even future releases of your current compiler.

Alan
Nov 21 '07 #3
Alan Woodland wrote:
Thanks. It's funny, I'd never actually though about the implications
of that in this context before. Just found the following quote which
ought to convince certain people:
Event funnier: According to 5.2.5, this code:
struct X { static const int x=0; };
int main() {
X*x=0;
x->n;
}

invokes UB.

And if I'd was not to lazy to look it up, I could tell you if

struct X { enum {x=0}; };
int main() {
X*x=0;
x->n;
}

invokes UB or not.

(I mean, they could really make an appendix "Authoritative List of
UB's", because it's really a nuisance to find these only scattered
around in the Standard)

--
IYesNo yes=YesNoFactory.getFactoryInstance().YES;
yes.getDescription().equals(array[0].toUpperCase());
Nov 21 '07 #4
Marco Manfredini wrote:
Alan Woodland wrote:
>Thanks. It's funny, I'd never actually though about the implications
of that in this context before. Just found the following quote which
ought to convince certain people:

Event funnier: According to 5.2.5, this code:
struct X { static const int x=0; };
int main() {
X*x=0;
x->n;
}

invokes UB.

And if I'd was not to lazy to look it up, I could tell you if

struct X { enum {x=0}; };
int main() {
X*x=0;
x->n;
}

invokes UB or not.

(I mean, they could really make an appendix "Authoritative List of
UB's", because it's really a nuisance to find these only scattered
around in the Standard)
I am not sure how such a list would help. You would still have to
understand that the postfix expression (x->) dereferences the pointer
regardless what's following it. How would mentioning that if one
dereferences a null pointer it's UB help understanding that x->n
does in fact dereference 'x' (if 'n' is a static member)?

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Nov 21 '07 #5
On Nov 21, 4:29 pm, Alan Woodland <aj...@aber.ac.ukwrote:
The Standard says that "p->" is
converted to "(*p)." (see section 5.2.5) and no matter how you slice it,
*p is a dereference. Dereferencing a null pointer results in undefined
behaviour.
Yes, but doing this:

sizeof( static_cast<P*>(0)->member ); //or
sizeof( *static_cast<P*>(0)->member )

would not invoke cause behavior (for interest sake) as
this dereference is "sliced" at compile time.

W
Nov 21 '07 #6
Victor Bazarov wrote:
>(I mean, they could really make an appendix "Authoritative List of
UB's", because it's really a nuisance to find these only scattered
around in the Standard)

I am not sure how such a list would help. You would still have to
understand that the postfix expression (x->) dereferences the pointer
regardless what's following it. How would mentioning that if one
dereferences a null pointer it's UB help understanding that x->n
does in fact dereference 'x' (if 'n' is a static member)?
Well, for an example 5.2.5 just says that x->y is dereferenced during
evaluation. So glancing over the paragraph I might remember that
"dereference" can invoke UB, but what are the details? If *what* is
dereferenced? And then there is sizeof (and soon decltype) which do not
evaluate their argument - so am I getting this right that sizeof(x->y)
should always be defined? I remember that there was a debate about that
question some time ago on clmc++.

So I think, that it would be nice, if an (effectual) Appendix would turn
the UBs inside out and list all UBs with pointers back to the context
of their premises, like:

Dereferencing
If t is of pointer type T and *t(1) is evaluated(2) and t does not point
to an object of type T (3), it's UB

(1) When is *t implicitely formed?: see "->"
(2) When is *t not evaluated? see: sizeof, decltype
(3) How can t not point to an object of it's declared type: see union,
reinterpret_cast, null pointer etc..

I bet that was shocking!

--
IYesNo yes=YesNoFactory.getFactoryInstance().YES;
yes.getDescription().equals(array[0].toUpperCase());
Nov 21 '07 #7
On Nov 22, 5:59 am, Marco Manfredini <ok_nospam...@phoyd.netwrote:
>
Event funnier: According to 5.2.5, this code:
struct X { static const int x=0; };
int main() {
X*x=0;
x->n;
}

invokes UB.
It requires a diagnostic, as X has no member 'n'.
struct X { enum {x=0}; };
int main() {
X*x=0;
x->n;
}

invokes UB or not.
Also requires a diagnostic, as X has no member 'n'.
Nov 22 '07 #8
Old Wolf wrote:
On Nov 22, 5:59 am, Marco Manfredini <ok_nospam...@phoyd.netwrote:
>Event funnier: According to 5.2.5, this code:
struct X { static const int x=0; };
int main() {
X*x=0;
x->n;
}

invokes UB.

It requires a diagnostic, as X has no member 'n'.
Thank you for your time.

s/int x=0/int n=0/g

Nov 22 '07 #9
On Nov 21, 7:15 pm, Marco Manfredini <ok_nospam...@phoyd.netwrote:
Victor Bazarov wrote:
(I mean, they could really make an appendix "Authoritative List of
UB's", because it's really a nuisance to find these only scattered
around in the Standard)
I am not sure how such a list would help. You would still have to
understand that the postfix expression (x->) dereferences the pointer
regardless what's following it. How would mentioning that if one
dereferences a null pointer it's UB help understanding that x->n
does in fact dereference 'x' (if 'n' is a static member)?
Well, for an example 5.2.5 just says that x->y is dereferenced
during evaluation. So glancing over the paragraph I might
remember that "dereference" can invoke UB, but what are the
details? If *what* is dereferenced?
The pointer. Dereferencing is a run-time action, the result of
the * operator.
And then there is sizeof (and soon decltype) which do not
evaluate their argument - so am I getting this right that
sizeof(x->y) should always be defined?
Yes. The standard explicitly says that the arguments to sizeof
are not evaluated. No run-time behavior.
I remember that there was a debate about that question some
time ago on clmc++.
So I think, that it would be nice, if an (effectual) Appendix
would turn the UBs inside out and list all UBs with pointers
back to the context of their premises,
There's not much to say about pointers: dereferencing a null
pointer, or a pointer to one past the end of an array, is
undefined behavior (in C++---in C, there are certain special
cases where one past the end of an array is allowed).
like:
Dereferencing
If t is of pointer type T and *t(1) is evaluated(2) and t does not point
to an object of type T (3), it's UB
(1) When is *t implicitely formed?: see "->"
Implicit or explicit has nothing to do with it. If the standard
says (and it does) that p->f() has the semantics of (*p).f(),
then it has the semantics of (*p).f(). I don't see what more
needs to be said.
(2) When is *t not evaluated? see: sizeof, decltype
Again, the standard is fairly explicit, although perhaps not
where you'd expect. §3.2/1: "An expression is potentially
evaluated unless it is either the operand of the sizeof
operator, or the operand of the typeid operator and does not
designate an lvalue of polymorphic class type."
(3) How can t not point to an object of it's declared type:
see union, reinterpret_cast, null pointer etc..
A pointer value can be considered as having one of four
categories:

-- it points to an object (no problem there),

-- it points to one past the end of an array (dereference
illegal, but pointer arithmetic still allowed).

-- it is null (no dereference, and I think, no pointer
arithmetic---but I'm not sure about p+0), and

-- anything else (nothing allowed, even lvalue to rvalue
conversion is undefined behavior)

With regards to unions, nothing changes. A union contains one
(and only one) of its members at a time. Any attempt to access
any other member is undefined behavior.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Nov 22 '07 #10
On Nov 21, 6:42 pm, werasm <wer...@gmail.comwrote:
On Nov 21, 4:29 pm, Alan Woodland <aj...@aber.ac.ukwrote:
The Standard says that "p->" is
converted to "(*p)." (see section 5.2.5) and no matter how you slice it,
*p is a dereference. Dereferencing a null pointer results in undefined
behaviour.
Yes, but doing this:
sizeof( static_cast<P*>(0)->member ); //or
sizeof( *static_cast<P*>(0)->member )
would not invoke cause behavior (for interest sake) as
this dereference is "sliced" at compile time.
There's no slicing involved, but the standard explicitly says
that the arguments of sizeof are not evaluated, so no runtime
undefined behavior can result.

Note that the fact that they are not evaluated has other
implications as well. For example, if you write "sizeof(f())",
you're not required to provide an implementation of f. And if
you write "sizeof(f<int>())", the template function f is not
instantiated for int.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Nov 22 '07 #11
On Nov 22, 2:53 pm, James Kanze <james.ka...@gmail.comwrote:
On Nov 21, 6:42 pm, werasm <wer...@gmail.comwrote:
On Nov 21, 4:29 pm, Alan Woodland <aj...@aber.ac.ukwrote:
The Standard says that "p->" is
converted to "(*p)." (see section 5.2.5) and no matter how you slice it,
*p is a dereference. Dereferencing a null pointer results in undefined
behaviour.
Yes, but doing this:
sizeof( static_cast<P*>(0)->member ); //or
sizeof( *static_cast<P*>(0)->member )
would not invoke cause behavior (for interest sake) as
this dereference is "sliced" at compile time.

There's no slicing involved, but the standard explicitly says
that the arguments of sizeof are not evaluated, so no runtime
undefined behavior can result.
I was not referring to slicing in C++, but to Alan's use of it (i.e
"no matter how you "cut/slice/look at" it).
Note that the fact that they are not evaluated has other
implications as well. For example, if you write "sizeof(f())",
you're not required to provide an implementation of f. And if
you write "sizeof(f<int>())", the template function f is not
instantiated for int.
Yes, this is typically used in SFINAE. Good to mention.

Regards,

Werner

Nov 22 '07 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

24
by: DaKoadMunky | last post by:
I was recently reading an article about sequence points that used the canonical i = i++; as an illustration of modifying a variable multiple times between sequence points. Curiously the...
2
by: Daniel Schüle | last post by:
Hi all! given the following code #include <iostream> using std::cout; using std::endl; struct X
5
by: Sumeet | last post by:
I met a question in a test which invoked undefined behaviour and i was asked to answer the Expected answer of the question Specifications := Win98 Os Tc compiler int i=23; i=(i++|++i)^(i++ +...
25
by: Nitin Bhardwaj | last post by:
Well, i'm a relatively new into C( strictly speaking : well i'm a student and have been doing & studying C programming for the last 4 years).....and also a regular reader of "comp.lang.c" I...
12
by: RoSsIaCrIiLoIA | last post by:
On Mon, 07 Feb 2005 21:28:30 GMT, Keith Thompson <kst-u@mib.org> wrote: >"Romeo Colacitti" <wwromeo@gmail.com> writes: >> Chris Torek wrote: >>> In article <4205BD5C.6DC8@mindspring.com> >>>...
19
by: Sharath A.V | last post by:
I had an argument with someone on wheather this piece of code can invoke undefined bahaviour. I think it does not invoke any undefined behaviour since there is sufficient memory space of 9...
26
by: Frederick Gotham | last post by:
I have a general idea of the different kinds of behaviour described by the C Standard, such as: (1) Well-defined behaviour: int a = 2, b = 3; int c = a + b; (Jist: The code will work...
12
by: Franz Hose | last post by:
the following program, when compiled with gcc and '-std=c99', gcc says test.c:6: error: jump into scope of identifier with variably modified type that is, it does not even compile. ...
10
by: subramanian100in | last post by:
Consider the following code: #include <iostream> #include <cstdlib> using namespace std; int main() { const double& ref = 100;
33
by: coolguyaroundyou | last post by:
Will the following statement invoke undefined behavior : a^=b,b^=a,a^=b ; given that a and b are of int-type ?? Be cautious, I have not written a^=b^=a^=b ; which, of course, is undefined....
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.