-1

Just a curious question. What happens if i try to access data from an address that has NULL value. for eg: If i have a structure pointer ulog which stores NULL and the compiler (in my case GCC) comes across ulog->data=12 ?

I wanna know majorly if this messes with my memory, is NULL returned when used with control statement and what goes down with the compiler ?

clinnsin
  • 15
  • 4
  • 1
    The compiler won't/won't need to complain. In run-time the program will abort with seg fault. – Paul Ogilvie Oct 17 '18 at 11:35
  • 1
    Dereferencing a null pointer leads to [*undefined behavior*](https://en.wikipedia.org/wiki/Undefined_behavior), and if using the pointer to write some data (like in your example assignment) then you will most likely have a crash. ***Always*** check pointers. – Some programmer dude Oct 17 '18 at 11:36
  • The compiler doesn't care, you are the programmer... The OS surely will get very disappointed... – Frankie_C Oct 17 '18 at 11:36

2 Answers2

2

To clear out the terms:

  • The macro NULL is a null pointer constant (7.19/3).
  • A null pointer constant is either the value 0 or (void*)0 (6.3.2.3/3).
  • When a null pointer constant is assigned to a pointer of any type, the resulting pointer becomes a null pointer which is guaranteed to compare unequal to any other pointer (which is pointing to an object or function) (6.3.2.3/3).

You can't really know the actual representation of a null pointer on the given system. What happens if you try to access it as if it was a valid address is not specified by the standard - it is undefined behavior.

Meaning that anything can happen, including segmentation faults, bus errors, nothing at all, program starting to run amok etc etc.

Lundin
  • 195,001
  • 40
  • 254
  • 396
1

The compiler won't complain.

However, in runtime, you will invoke Undefined Behavior (UB), since you are dereferencing a NULL pointer.

gsamaras
  • 71,951
  • 46
  • 188
  • 305