2

In this post, it is cleared say that (C99 definition 6.3.2.3p3 says)

If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

But in this answer, @Joey Adams use the following macro:

#define member_size(type, member) sizeof(((type *)0)->member)

It seems that he use a null pointer to access a member (an array in this case) and he use this to know the size of a member. In the following assembly code(example from the same question), it has been already substitute by a number.

movl    $255, %esi   ---> printf("%lu",member_size(Parent, text));
movl    $.LC0, %edi
movl    $0, %eax
call    printf

So it seems that it has 'accessed' the member and become the assembly code. But in the comment, he said 'it isn't actually dereferenced' and make me confused.

So my question:

  • when is exactly the number calculated?

  • why it can be accessed using a null pointer?

Community
  • 1
  • 1
Tony
  • 5,972
  • 2
  • 39
  • 58
  • 4
    `sizeof` does not evaluate its operand (except in rare cases eg VLA) – pmg Aug 02 '14 at 09:18
  • @pmg I don't understand why VLA should be an exception to the rule that `sizeof` does not evaluate its operands. If `p` is a pointer to a VLA, then `sizeof *p` is determined **entirely on the base of its type** to be that size that **will have been previously evaluated at run-time** and stored somewhere safe for future reference. What would an example be of `sizeof` evaluating its operand? – Pascal Cuoq Aug 02 '14 at 09:50
  • @pmg But the member of the parent is a array, why it doesn't evaluate? – Tony Aug 02 '14 at 09:55
  • 1
    see [example at ideone](http://ideone.com/bSgLZX). – pmg Aug 02 '14 at 10:07
  • Oh, thanks. And sorry for duplicate. – Tony Aug 02 '14 at 10:10
  • @pmg Thanks. You may have found a bug in Frama-C (http://frama-c.com/ ). – Pascal Cuoq Aug 02 '14 at 10:13
  • @PascalCuoq: that was not my idea, but I'm happy to have unearthed a bug :) – pmg Aug 02 '14 at 10:58
  • @PascalCuoq also see [my answer here](http://stackoverflow.com/a/21995718/1708801) – Shafik Yaghmour Aug 02 '14 at 11:20

0 Answers0