
I didn’t cause a lot of discussion about whether it is permissible to use the expression & P-> m_foo in C / C ++ if P is a null pointer. Programmers are divided into two camps. Some confidently argued that it was impossible to write this way, others just as confidently asserted that it was possible. There were various arguments and references. And I realized that I need to bring final clarity to this question. To do this, I turned to Microsoft MVP experts and Visual C ++ developers who communicate through a closed mailing list. They helped prepare this article, and I present it to anyone. For impatient: this code is not correct.
I will remind the discussion history
It all started with an
article about checking the Linux kernel with the help of the PVS-Studio analyzer. But the kernel check itself has nothing to do with it. The fact is that in the article I gave the following fragment from the Linux code:
static int podhd_try_init(struct usb_interface *interface,
struct usb_line6_podhd *podhd)
{
int err;
struct usb_line6 *line6 = &podhd->line6;
if ((interface == NULL) || (podhd == NULL))
return -ENODEV;
....
}
, ,
.
. ,
offsetof, :
#define offsetof(st, m) ((size_t)(&((st *)0)->m))
, . , , .
, . : "
".
, . . .
, , . , . .
'&podhd->line6' C , 'podhd' — .
'&' C99 ( 6.5.3.2 « »):
& , [] *, lvalue-, , .'podhd->line6' , [] *. lvalue-. , 'podhd' , , 6.3.2.3 «» :
, , , .«lvalue- , » ( C99, 6.3.2.1 «Lvalue-, »):
lvalue — , void; lvalue- , .:
-> , lvalue-, , .
++
++ . '&podhd->line6' C++ , 'podhd' — .
WG21 (
232. Is indirection through a null pointer undefined behavior?), . , . C++, «poldh->line6», «polhd» — .
«polhd» ( 5.2.5/4, ) , . C++ nullptr.
struct usb_line6 *line6 = &podhd->line6;
++, podhd 0. 0, .
, , . , . , , . , .
. .
- offsetof() , . , offsetof(), , '&podhd->line6' , 'podhd' .
- GCC ( ) , , , — , . , "What Every C Programmer Should Know About Undefined Behavior #2/3".
- , , TUN/TAP-. "Fun with NULL pointers". , , : TUN/TAP- , , . C .
- - , P == nullptr &P->m_foo ? , sizeof: sizeof(&P->m_foo).
, , . :
- — C/C++ , Windows, . StackOverflow, C C++ ( C#). 6 Microsoft MVP Visual C++.
- ' — C++ () StackOverflow. - Microsoft (Trustworthy Computing Team). , , — Malware Bytes PreEmptive Solutions.
- — , Windows. C++, OpenGL . . , , C C++, Microsoft MSDN, — StackOverflow. 8 Microsoft MVP Visual C++.
- — - Microsoft. C++-. — . , Microsoft, A&M (Texas A&M University). 2012 (National Science Foundation CAREER Award) . C++.
- Wikipedia. .
- A Guide to Undefined Behavior in C and C++. Part 1, 2, 3.
- Wikipedia. offsetof.
- LLVM Blog. What Every C Programmer Should Know About Undefined Behavior #2/3.
- LWN. Fun with NULL pointers. Part 1, 2.