0

I know about a feature, when we can get an offset of struct member via NULL or invalid pointer, like here:

#include<stdlib.h>
#include<stdio.h>
typedef struct  A {
        int c;
        int b;
} A;
int main() {
        A *a = (A*)0x100;
        fprintf(stderr, "%p\n", &((*a).b));
        fprintf(stderr, "%p\n", &a->b);
}

This program produces:

0x104
0x104

Is there a way to disable this feature and get a segfault or error instead?

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
peroksid
  • 357
  • 3
  • 14
  • 2
    Just deference the pointer to give you the segfault. All you are doing is printing pointer values. It is not a "feature" that you can "disable". – Weather Vane Dec 17 '16 at 20:51
  • @Weather Vane , I dereference the pointers, for example here "&a->b" - 1)dereference a, 2)get b, 3)get address of b. – peroksid Dec 17 '16 at 20:57
  • 3
    No, that is just an address, not its data. You do not try to get the *value of* `b`. Which is why you did not get a segfault. – Weather Vane Dec 17 '16 at 20:58
  • If you want to get the offset of a `struct` member, use the standard `offsetof` macro. Don't use very questionable hacks, they can (and increasingly will) result in unexpected behaviour of your code with modern compilers and in modern C. – too honest for this site Dec 17 '16 at 22:17
  • How do you expect to change compiler behaviour? By passing flags to it? You need to study *your* compiler and its flags then. – n. m. could be an AI Dec 18 '16 at 08:59

1 Answers1

1

You example is arguably undefined behavior.

As such you can't expect to get a segmentation fault, which is a feature of the hardware anyway.

There is no way of guaranteeing that your example, or just a plain dereference of a null pointer will trigger the fault.

2501
  • 25,460
  • 4
  • 47
  • 87