Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to safely check for null pointers

Tags:

c++

(Using visual studio 2010)

I have a simple returnLength() function for a list, defined simply as

int returnLength() 
{
    if (!next) return 1;
    else return 1 + next->returnLength();
}

next is a pointer to another node in the list. When checking the if statement to check if next is valid, Visual Studio is throwing a runtime error citing Access violation. This error is occurring several calls deep into the recursion tree.

What is the recommended way to check whether a pointer exists?

like image 214
pbj Avatar asked Dec 10 '22 10:12

pbj


1 Answers

That is a valid way. What's likely happening here is that this is NULL and hence you're getting an access violation trying to read next off of NULL pointer. You need to check for NULL at the callsite to returnLength

like image 160
JaredPar Avatar answered Dec 22 '22 03:12

JaredPar