Some subsurface notes from a week of diving
Lubomir I. Ivanov
neolit123 at gmail.com
Mon Mar 17 13:26:19 PDT 2014
On 17 March 2014 21:28, Thiago Macieira <thiago at macieira.org> wrote:
> Em seg 17 mar 2014, às 11:12:31, Linus Torvalds escreveu:
>> The compiler is allowed to assume that the *result* of the arithmetic is
>> not NULL, because pointer arithmetic is only well-defined if it stays
>> within an object, and that explains the offsetof thing you point to (since
>> that very much uses the result). Even then, a compiler that actually
>> miscompiles the traditional format is just crap.
>
> Indeed:
>
> struct D { int i; int j; };
> int f(struct D *d)
> {
> int *p = &d->j;
perfectly valid for d == NULL, even if not mentioned in the standard
and i seriously doubt it is.
the pointer d is just an address with a type, where j is just an
offset from that address based on the type (struct declaration).
the compiler has the offsets for a struct declarations in memory while
dealing with a source file and each time that struct type is
encountered it can potentially just geberate ADD instructions, e.g:
addl $4, %eax
where %eax previously holds the d argument, %eax now holds the address of j
C compilers do not check if &d is NULL, to my knowledge.
if it's the other way around it would basically limit the language,
because one can still do pointer arithmetic with *p even if equal to
0x4.
prone to programmer errors? yes.
> if (!p)
> return -1;
> return *p;
> }
>
> Clang 3.4 removes the check for !p. ICC 14.0 and GCC 4.9 don't.
>
quite bogus; i don't see why clang removes the check for !p.
if d is NULL then p cannot be NULL, because j it's not the first
element in the struct and it would be 0x4 or (&d + offset).
if (return *p;) is reached that's a definitive SIGSEGV later, because
that memory won't be accessible.
in that matter:
&some_func()->j
is also valid where some_func() returns (struct *D), but if the
address of the pointer is NULL:
&some_func()->j will still evaluate to 0x4.
lubomir
--
More information about the subsurface
mailing list