Xylene23 Xylene23 - 1 month ago 17
C Question

Null assignment

#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.

Answer

[..] 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); 
Comments