1
int (*a)[10] = NULL; // initilaized to NULL pointer

printf("a  :: %p\n", a); // print nil
printf("*a :: %p\n", *a); // seg fault??

return 0;

I executed this code on my x86 code using gcc, and it compiles without any error.
I expected something like

a :: (nil)
Segmentation Fault

but it actually prints out

a :: (nil)
*a :: (nil)

Why here referencing null pointer does not cause seg fault?

1
  • 2
    Dereferencing a NULL pointer is Undefined Behaviour. There's no guarantee that it will result in a seg fault. So you need to adjust your expectation. Commented Oct 5, 2020 at 5:34

2 Answers 2

1

The reason in general is that dereferencing a pointer to array does not read any memory, the result is an array having same address - the result is just a different type.

The behaviour is undefined nevertheless.

Note that you used %p but you could have used %s for the second one (with char (*a)[10] = NULL;) which would have even more undefined behaviour, and yet still GCC/Glibc printf would often print (nil) instead of crashing.

Sign up to request clarification or add additional context in comments.

Comments

0

That's because this is undefined behaviour, anything can happen on any compiler and even different versions of a compiler.

You are using gcc and the code that gcc generates is merely that it moves NULL (a zero) to rax which does not segfault.

mov     QWORD PTR [rbp-8], 0
mov     rax, QWORD PTR [rbp-8]
mov     QWORD PTR [rbp-16], rax

You can see assembler output for C programs with different versions of gcc at

https://godbolt.org/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.