In C/C++, there are some ground rules programmers should follow that can make their lives dealing with pointers so much easier. Even though the term "invalid pointer" is not defined in the C/C++ terminology, there are a few cases in which the programmer breaks these ground rules. We'll go through these one by one.
Firstly, a pointer can only point to a location inside memory that was previously allocated in the code. For example, if an integer arr
array of size s
is defined, the programmer should not access the element, arr[s]
. If they try to access it, the compiler will either throw a memory out-of-bounds exception or return a garbage value (this varies from compiler to compiler, depending on its strictness).
Below is an illustration of the iteration of an array of size 4, but the programmer tries to access one element ahead of the actual size of the array.
Secondly, a pointer will be invalid if it does not point to anything. This case will occur if a user points a pointer towards a dynamically allocated memory location, deallocates that dynamically allocated memory, and forgets to delete the pointer that was pointing to that location or point it to NULL. An example of this occurring in code is shown below.
It is important to note here that the keyword delete
in C++ only frees the memory that was previously allocated. This means that the OS can utilize this memory location for another task now, and the pointer that points to this location is not deleted. Rather, it points to a memory location that is not allocated, as shown in the illustration below.
This is dangerous, as this pointer will be accessing an invalid memory location, and this is not good programming practice because if this is allowed, then it can be exploited to perform attacks like the buffer overflow attack. To mitigate this, the pointer should be pointed towards NULL.