-1

I am checking to see if a pointer exists and if it does exist then it doesn't point to a NULL/zero value. My code looks like this:

if (prior != NULL && *prior){
  //do something
}

Where prior is a pointer. However, I am getting a segmentation fault on *prior. But I don't understand how this is possible. The if-statement should short circuit if prior is a NULL pointer, so *prior should always work.

Any ideas?

foobar5512
  • 2,470
  • 5
  • 36
  • 52

1 Answers1

3
if (prior != NULL && *prior){
    //do something
}

There are more reasons to segfault than just dereferencing a NULL pointer. The pointer may be not NULL, yet if you are deference an invalid or dangled pointer, your program can still segfault.

Revisit this well-known answer about pointer: Can a local variable's memory be accessed outside its scope?

which also explains why a pointer can be non NULL yet still invalid.

Community
  • 1
  • 1
artm
  • 17,291
  • 6
  • 38
  • 54
  • [Reworking comments into answers](https://meta.stackoverflow.com/questions/253045/answerers-who-only-use-comments) is acceptable behaviour. – Ken Y-N Dec 01 '16 at 00:29
  • 1
    @KenY-N you can't say that it's a rework unless there is a significant time difference between a comment and a more complete answer. – artm Dec 01 '16 at 00:36
  • @artm this is an online community, there are all sorts of people, you don't let your feelings down just because some random unpleasants. – fluter Dec 01 '16 at 00:49
  • @fluter absolutely – artm Dec 01 '16 at 00:54