-2

I am trying to explore the pointers in C, so pretty new to this subject. I came to know that best practice is to assign "NULL" when declaring a pointer. So in the below program I did the same:

#include <stdio.h>
int main() {

 unsigned int *ip = NULL;

 printf("Address stored in pointer: %x \n",ip); //gives 0
 printf("Value stored at Address stored in pointer: %d \n",*ip); // gives "Segmentation fault (core dumped)"

 return 0;

}

I am not able to understand clearly why this is happening. Shouldn't it output a value (NULL or something).

I am using centos 6.5 and gcc version 4.4.7.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
vsingh
  • 470
  • 4
  • 9
  • possible duplicate of [dereferencing the null pointer](http://stackoverflow.com/questions/2896689/dereferencing-the-null-pointer) – 2501 Oct 14 '14 at 13:41
  • 1
    Why do you say that "it should output a value" ? Where have you read that ? because what you have read would be false. – Stephane Rolland Oct 14 '14 at 13:42
  • 2
    This is why setting pointers to NULL is good practice. So you get an error if you dereference it. Use %p to print a pointer. – Neil Kirk Oct 14 '14 at 13:43
  • `*ip` dereferences a null pointer and this usually leads to a crash on modern systems (MacOS, Windows, Linux). – Jabberwocky Oct 14 '14 at 13:45
  • Thanks all for sharing your insights...i also took a look in the link by @2501.. – vsingh Oct 14 '14 at 13:56
  • @NeilKirk..that tip made the warnings disappear "warning: format ‘%x’ expects type ‘unsigned int’, but argument 2 has type ‘unsigned int*" :) – vsingh Oct 14 '14 at 14:06

1 Answers1

3

People assign NULL to pointer to indicate that it points to nothing.

Dereferencing pointer pointing to memory which doesn't belong to your program
(NULL==0, and address 0 belongs to your operating system) is undefined behaviour.

People assign NULL to pointers to be able to write

if(ip) //NULL==0==false, so the condition means "if ip points to something"
    printf("Value stored at Address stored in pointer: %d \n",*ip);
else printf("The pointer points to NULL, it can't be dereferenced\n");
GingerPlusPlus
  • 5,336
  • 1
  • 29
  • 52