473,549 Members | 2,781 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1530
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
"dereferenc e 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
"dereferenc e 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 "Authoritat ive List of
UB's", because it's really a nuisance to find these only scattered
around in the Standard)

--
IYesNo yes=YesNoFactor y.getFactoryIns tance().YES;
yes.getDescript ion().equals(ar ray[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 "Authoritat ive 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 "Authoritat ive 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
"dereferenc e" 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_cas t, null pointer etc..

I bet that was shocking!

--
IYesNo yes=YesNoFactor y.getFactoryIns tance().YES;
yes.getDescript ion().equals(ar ray[0].toUpperCase()) ;
Nov 21 '07 #7
On Nov 22, 5:59 am, Marco Manfredini <ok_nospam...@p hoyd.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...@p hoyd.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...@p hoyd.netwrote:
Victor Bazarov wrote:
(I mean, they could really make an appendix "Authoritat ive 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 "dereferenc e" 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_cas t, 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 objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Nov 22 '07 #10

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

Similar topics

24
1578
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 article did not indicate the type of i. Is it fair to say that if i was an instance of a class type that overloaded
2
1319
by: Daniel Schüle | last post by:
Hi all! given the following code #include <iostream> using std::cout; using std::endl; struct X
5
1660
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++ + ++i); what should be the value of i after this ? is there any way that i can predict the answer ? Also i don't have a good understanding of the...
25
3068
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 don't have a copy of ANSI C89 standard,therefore i had to post this question: What is the difference between "unspecified" behaviour & "undefined"...
12
1791
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> >>> pete <pfiland@mindspring.com> wrote: > >>> >If you have >>> > int array; >>> >then
19
1770
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 integer elements starting from the in the address passed, but the other person insisted that it would invoke undefined behaviour(for whatever reasons he...
26
2162
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 perfectly.)
12
5658
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. lcc-win32, on the other hand, reports Warning test.c: 7 unreachable code
10
1791
by: subramanian100in | last post by:
Consider the following code: #include <iostream> #include <cstdlib> using namespace std; int main() { const double& ref = 100;
33
2803
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. I am having some confusion with the former statement! Also, state the reason for the statement being undefined!
0
7520
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7450
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7720
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7470
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7809
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6043
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5368
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3481
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1941
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.