how to check if a pointer is valid or not in C++

So here we are going to study about how to check if a pointer is valid or not in C++.

Invalid Pointers in C++

Let us discuss the types of invalid pointers. There are mainly 3 kinds of invalid pointers.

The first is a null pointer. The null pointers could be checked easily we do not have to use any function . for example, a strcpy gives exception if string is not assigned with memory.

Another example is strcmp if any of the string is initialized with valid pointer the program will stop and the structured exception will be thrown.

The second type of invalid pointer is a pointer already deleted but used after deletion. That form is specified as if you return a pointer to a local memory which was deleted or removed from memory automatically after the return.

The third kind is a corrupted or uninitialized pointer which means that the address was not returned by ‘new’ operator. Another reason for uninitialized pointer maybe the address of an existing object was not found.  The third kind of invalid pointers isn’t a case that should be handled but you need to find the cause for the corruption.

Memory corruption like not having assigned memory.

Then also it searches in memory buffer will lead to harm in program as well as pointer initialization.

You may read: Pointers and references in C++

Check if a pointer is valid or not in C++

To check if a pointer is valid when using pointers concept first initialize all pointers to zero.

Then if you cannot find any pointer initialization then check that it is non-0 before deleting it.

When we delete a pointer first we have to make the pointer point to null then delete it.

By the below code we can check if pointer valid or not

if ( ptr->value == NULL ) {
//pointer is invalid
}
else
//pointer is valid

So if ptr-> value means we check if a value is assigned or not if it is not assigned means the memory is not given

So null it is an invalid pointer and hence we cannot use it.

The else specifies that the value is provided and hence pointer is valid.

Leave a Reply

Your email address will not be published. Required fields are marked *