Dangling, Void , Null and Wild Pointers

dangling-void-and-null-pointer-in-c

Despite the fact that pointers are an important tool, sometimes code getting the crash due to improper use of pointers. If you do not use the pointers in a proper way, the pointer can become the curse and it can create a very crucial issue (segmentation fault or bus error).

I have written many articles to describe the benefits of pointers but I think it is also important to familiarize the people from the diverse effects of the pointer.So in this article, I am describing different states of the pointer with common tips to protect the code with the bad effect of pointers.

Recommended article: all about pointer in c




What are dangling pointers?

Generally, daggling pointers arise when the referencing object is deleted or deallocated, without changing the value of the pointers. It creates the problem because the pointer is still pointing the memory that is not available. When the user tries to dereference the daggling pointers than it shows the undefined behavior and can be the cause of the segmentation fault.

In simple word, we can say that dangling pointer is a pointer that not pointing a valid object of the appropriate type and it can be the cause of the undefined behavior.

Let’s see the below image for the better understanding.

In the image Pointer1, Pointer2 are pointing a valid memory object but Pointer3 is pointing a memory object that has been already deallocated. So Pointer3 become a dangling pointer when you will try to access the Pointer3 than you will get the undefined result or segmentation fault.

dangling pointer

Important causes of the dangling pointers in C language

There a lot of cause to arise the dangling pointers but here I am describing some common cause that creates the dangling pointers.

When variable goes out of the scope

A local variable’s scope and lifetime belong to their block where it is declared. Whenever control comes to the block than memory is allocated to the local variable and freed automatically upon exit from the block.

If a local variable is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the variable it points to reaches the end of its lifetime.

Let see the below code for the better understanding.

In the below code, we have tried to read the value of Data (integer variable) outside of their block (scope) through the pointer (piData), so the value of piData is indeterminate.

After destroying the stack frame

The stack frame that is allocated to a function is destroyed after returning the control from the function. The common mistake performed by the developer is that to return the address of the stack allocated variable from the function. If you tried to access the returning address from the pointer, you will get the unpredictable result or might get the same value but it is very dangerous and need to avoid.

Let see the below programming example,

In below code, Data has not scope beyond the function. If you try to read the value of Data after calling the Fun() using the pointer may you will get the correct value (5), but any functions called thereafter will overwrite the stack storage allocated for Data with other values and the pointer would no longer work correctly.

So in the below code piData is a dangling pointer that is pointing a memory which is not available.




Deleting the memory explicitly

The compiler handles static and auto allocated memory but if the user allocates the memory manually than it is the responsibility of the user to free the manually allocated memory. In the C language malloc, calloc and realloc library function are used to allocate the memory at runtime and free is used to deallocate the allocated memory. The jumbled combination of malloc (calloc, realloc) and free is born the dangling pointers.

A problem is invoking, whenever programmer has freed the allocated memory and try to access the freed memory. You will be lucky if you will not get the segmentation fault after using the freed memory. It is a very common mistake that is generally done by the developers.

How to avoid the dangling pointers errors

The behavior of the dangling pointer is undefined, so it is very important to avoid the born of dangling pointers. The common mistake that is done by many programmers is that not assigning the NULL explicitly after freeing the dynamic memory. So It is very good habits to assign the NULL after deallocation of the dynamically allocated memory.

Apart from that, another mistake is to return the address of the local variable (stack variable) from the function, it is also a cause to create a dangling pointer.Using the static variable we can resolve the problem because the lifetime of the static variable is entire run of the program.




What is the wild pointer?

A pointer that is not initialized properly prior to its first use is known as the wild pointer. Uninitialized pointers behavior is totally undefined because it may point some arbitrary location that can be the cause of the program crash, that’s is the reason it is called a wild pointer.

In the other word, we can say every pointer in programming languages that are not initialized either by the compiler or programmer begins as a wild pointer.

Note: Generally, compilers warn about the wild pointer.

int *piData; //piData is wild pointer

What is a NULL pointer?

According to C standard, an integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer.

int *piData = NULL;  // piData is a null pointer

wild pointer

Few important points of the NULL pointer

  • According to C standard, 0 is also a null pointer constant.

Example,

int *piData = 0 ; // It is a legal statement and piData is a null pointer.

  • If we compare the null pointer from the pointer that’s is pointing to any object or function, the comparison shall be unequal. The uninitialized pointer does not give any such type of guarantee.
  • If we convert the null pointer to another pointer of type T, the resulting pointer will be a null pointer of that type T.
  • In C, two null pointers of any type are guaranteed to compare equal.
  • In C, if you try to dereference the NULL pointers, the result will be segmentation faults.
  • If T is a null pointer, &*T is equivalent to T.

Use of null pointer in C

  • A pointer that is not pointing the address of a valid object or valid memory should be initialized to NULL. It prevents the pointer to become a dangling pointer and ensure the programmer that pointer is not pointing anywhere.

char *pcData = NULL; //Prevent to become dangling pointer

  • A very good habit to check the validity of the pointers before using. It prevents from the crashing of the code and unwanted result. The null pointer helps you in error handling.

  • There are a lot of library function in C where pointer arguments are optional. So passing the null pointer to a function argument is useful when you don’t want to pass any valid memory or object address.

For example,

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);



What is void or Generic pointers in C?

A void pointer is a generic pointer, it has no associated data type. It can store the address of any type of object and it can be type-casted to any types. According to C standard, the pointer to void shall have the same representation and alignment requirements as a pointer to a character type.A void pointer declaration is similar to the normal pointer, but the difference is that instead of data types we use the void keyword.

Syntax:

void * Pointer_Name;

void *pvHandle; //pvHandle pointer to void

For more detail see this article:  Application of void pointer in C

Your opinion matters

In this article, I have tried to cover a lot of points for the different states of pointers with void and null pointer but I would love to know your opinion and issues which you have faced in your project. So please don’t forget to write a comment in the comment box.



2 comments

  1. Hi Amlendra,
    It is a nice article which covers lots of stuff at one page.
    I have a small doubt here.

    #include
    #include
    int main()
    {
    int *piData = NULL;
    piData = malloc(sizeof(int)* 10); //creating integer of size 10.
    free(piData); //free the allocated memory
    *piData = 10; //piData is dangling pointer
    return 0;
    }
    As you and many other sites also said that we can avoid dangling pointers by the following step:
    piData = NULL;
    Even if we do this, if I try to access the value as *piData I do get “Segmentation Fault”
    And if I don’t do also I get the “Segmentation Fault Or Core dump” in most cases.
    So, what is the necessity of assigning the pointer to NULL in this case.
    Sorry if someone feels it as a silly doubt.
    Thanks for the Article. Keep Continue to make this kind of articles. 🙂

    1. Hi Vijaya,

      Thanks for taking interest in my article. In C free function is used to deallocate the allocated memory but what happened after the deallocation of the memory the pointers still pointing the same address but now its address is not valid, some compiler assigned it NULL. SO for safety purpose, we need to assign the NULL to the pointer after the deallocation.

      int main(void)
      {
      int *pcBuffer = NULL;

      //creating integer of size n.
      pcBuffer = malloc(10 * sizeof(int));

      printf(” Address = %p\n”, pcBuffer);

      free(pcBuffer);

      printf(” Address = %p\n”, pcBuffer);
      return 0;
      }

      OutPut:

      Address = 00000000005555C0

      Address = 00000000005555C0

Leave a Reply