📜 ⬆️ ⬇️

Dereferencing a null pointer results in undefined behavior.

Silent NULL (null pointer dereference leads to undefined behavior)
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, .

, , . , . , , . , .

. .




, , . :


  1. Wikipedia. .
  2. A Guide to Undefined Behavior in C and C++. Part 1, 2, 3.
  3. Wikipedia. offsetof.
  4. LLVM Blog. What Every C Programmer Should Know About Undefined Behavior #2/3.
  5. LWN. Fun with NULL pointers. Part 1, 2.

')

Source: https://habr.com/ru/post/250701/


All Articles