How to change a compiler behaviour when getting a struct member via invalid pointer

73 views Asked by At

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?

1

There are 1 answers

0
2501 On

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.