1
#include<stdio.h>
#include<conio.h>

void main()
{
    int *p=NULL;
    *p=30;
    printf("%d %p", *p,p);  //output:- 30 0000
}

p should be pointing to address 0 and I think there should be null assignment error. But how *p is giving output as 30? Is 30 stored in location 0000? According to me 0th address should not be assigned to any variable.

Zephyr
  • 1,521
  • 3
  • 22
  • 42
  • Dereferencing a null-pointer is undefined, so there is no guarantee that an exception occurs. In this case the code might have been optimized in a way that the pointer is not used at all to store and retrieve the 30, e.g. by storing it in a register, as the code is quite simple. In more complicated situations, a segfault is more likely. – Karsten Koop Oct 13 '16 at 09:55
  • 1
    The behaviour might depend on the optimization settings of the compiler. – Karsten Koop Oct 13 '16 at 09:57
  • 4
    Just undefined behavior, anything can happen – Danh Oct 13 '16 at 09:58
  • 1
    Related question : http://stackoverflow.com/questions/39608081/is-a-null-pointers-dereference-also-equals-null/39608103#39608103 –  Oct 13 '16 at 10:00
  • On what system do you observe this beheaviour ? – Jabberwocky Oct 13 '16 at 10:09

1 Answers1

1

[..] I think there should be null assignment error.

C staandard doesn't provide any such guarantees.

Dereferencing a null pointer is undefined behaviour. So, there's no point in reasoning about why it prints 30. Btw, you should cast the pointer argument to void* to print it:

printf("%d %p", *p, (void*)p); 
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
P.P
  • 117,907
  • 20
  • 175
  • 238
  • Can you tell me the meaning of the output ? It is giving 30 so it means that *p is changing the value at address 0 to 30 right? – Zephyr Oct 13 '16 at 09:54
  • 3
    You are not allowed to dereference a null pointer (`*p = 30;` and in the printf). This usually raises a SIGSEGV on Linux but the behaviour may be different on differnt platforms. When it's undefined, it's ...undefined. There may be platform specific explanation for why it's 30 on your machine but it's generally useless. – P.P Oct 13 '16 at 09:57
  • Ok thanks. Can you tell me why (void *) cast is needed ? – Zephyr Oct 13 '16 at 09:59
  • 3
    The C standard requires the argument to match the format specifier (`void*` for `%p`). See [How to printf a memory address in C](http://stackoverflow.com/a/30354164/1275169). – P.P Oct 13 '16 at 10:03