Pointers such as Dangling, Void, Null, and Wild

Dangling pointer

A dangling pointer is a pointer that points to a deleted (or freed) memory location. Pointer can function as a dangling pointer in three ways.

1. De-allocation of memory

C++ Code

2. Function Call

C++ Code

C Code

Output:

A garbage Address

If x is a static variable, the above problem does not occur (or p does not become dangling).

C++ Code

Output:

5

3. Variable goes out of scope

Void pointer

Void pointer is a specific pointer type - void * - a pointer that points to an unspecified data location in storage. The type is referred to as void. Basically, the data that it points to can be anything. If we assign a char data type address to a void pointer, it will become a char pointer, an int data type address will become an int pointer, and so on. Because any pointer type can be converted to a void pointer, it can point to any value.

Important Considerations

  • It is not possible to dereference void pointers. However, it is possible to do so by typecasting the void pointer.
  • Due to the lack of a concrete value and thus size, pointer arithmetic is not possible on void pointers.

C++ Code

Output:

Integer variable is = 4
Float variable is= 5.500000

NULL pointer

C++ Code

Output:

The value of ptr is (nil)

Important Considerations

  • Uninitialized pointer vs. NULL - An uninitialized pointer stores an undefined value. A null pointer stores a defined value, but one that the environment defines as not being a valid address for any member or object.
  • NULL vs. Void Pointer - A value is a null pointer, whereas a void pointer is a type.

Wild pointer

A wild pointer is one that has not been initialised to anything (not even NULL). The pointer may be set to a non-NULL garbage value that is not a valid address.

C++ Code