-3

let's say I define a pointer variable to be of some class type ptrClass:

ptrClass *ptr;

and let's say this ptrClass has a member function called get() that returns a pointer that is pointing to nothing.

so if we do:

ptr->get();

this would result in a seg fault.

but if we do if(ptr->get()), this does not result in a seg fault (the if statement simply does not execute). Can someone explain why this is the case? In order to check the if statement condition, doesn't the program perform ptr->get(), which should result in seg fault?

DimChtz
  • 4,043
  • 2
  • 21
  • 39
roulette01
  • 1,984
  • 2
  • 13
  • 26
  • Can you show us a minimal example code that reproduces the error? We don't know anything about ptrClass – KABoissonneault Mar 31 '16 at 21:57
  • 1
    You simply have **undefined behavior** dereferencing an uninitialized `ptrClass *ptr;` pointer, which your sample proves well. – πάντα ῥεῖ Mar 31 '16 at 21:57
  • 1
    Using `ptr->get()` is undefined behavior when `ptr` does not point to a valid object. It's pointless trying to make sense of undefined behavior. By definition, it is undefined. Anything can happen. – R Sahu Mar 31 '16 at 21:58
  • And insightful http://stackoverflow.com/a/4286034/4743711 – Loreto Mar 31 '16 at 22:14

2 Answers2

1

Code with bugs in it will do things you don't expect. It really is that simple. Fix the bug and the mystery will go away.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
1

Calling method of invalid pointer is undefined behaviour, anything can happen.

You don't show what get() does but if get() does not use this and is not virtual, the programme will not dereference ptr so it won't use an invalid pointer.

StenSoft
  • 9,369
  • 25
  • 30