×

Dangling pointers in C

Dangling pointers in C: A pointer is a variable that stores the memory address of other variables. The pointers may also store the address of other’s memory items. They are of great help when it comes to dynamic memory allocation. A dangling pointer, on the other hand, points to a non-existential variable or a memory location. The dangling pointer may point to a variable or a memory location that might have been freed.

These pointers come into existence when the object or a variable or a memory location has been deleted or deallocated without modifying the value of that particular pointer.

In the C standard involving C pointers, many common bugs are occurred due to the pointers and managing the dangling pointers. Often, a programmer or a developer might fail to initialize the pointer with a valid address. That type of initialized pointer is known as a dangling pointer in C.

Dangling pointers mostly happen during the destruction of an object when it is being deleted or deallocated from memory without modifying the value of the pointer.

The dangling pointer can always point to a variable or memory location, consisting of the entire program code or the code of that particular operating system. If any value has been assigned to the dangling pointer, then it will overwrite that variable’s value of the program code or the operating system; in cases like such, the program will always show the undesirable result or even the crash.

If the memory is then reallocated in some other code, then the dereference of the dangling pointer will happen because of the segmentation fault. Since the value of the dangling pointer will not be modified at any time, it may still point to the memory locating of the other deallocated memory.

Dangling pointers may occur in three cases while executing a program:

  1. Function Call

A pointer pointing to a variable becomes a dangling pointer when the pointer pointing to the local variable is not a static variable.

E.g.:

 #include <stdio.h>
#include <conio.h>
int *myvalue()
{
int a=5;
return &a;
}
int main()
{
int *ptr=myvalue();
printf("%d", *ptr);
return 0;
}   

Output

Dangling Pointers In C

Explanation

  • Once the main() function is created where the pointer ‘ptr’ has been declared. It consists of the return value of the ‘myvalue()’.
  • Once the ‘myvalye()’ is called, then the control moves from one context to another which is an integer *myvalue(), the ‘myvalue()’ then returns to the address of the ‘a’ variable.
  • Once the control comes back to the main function, the variable will no longer be available. It causes segmentation fault, that is, the code will be dumped.

Hence, it is said that the pointer becomes a dangling pointer since it points to a memory location that has been freed or deleted. The variable ‘a’ is a static variable and this static variable stores in the global memory.

Variable out of the scope

When the variable is pointing to a variable and that particular variable goes out of scope, then that pointer is considered as a dangling pointer.

E.g.:

 #include <stdlib.h>
void main()
{
            int *ptr = NULL;
            {
                        int num;
                        ptr = #
                        //ptr is not dangling in the inner block
            }
            //ptr is dangling in the outer block as num is out of scope in this block
} 

Output

error

Deallocation of the memory

When the memory in the program is deallocated, then the pointer points to a freed or a deleted space which eventually leads to dangling pointer

E.g.:

 int main()
{
int *ptrr=(int *)malloc(sizeof(int));
int x=80;
ptrr=&x;
free(ptrr);
return 0;
} 

Output

Dangling Pointers In C

How to avoid dangling pointers

The dangling pointer gives out bugs and errors in the C programming language and it becomes difficult for a programmer to find one. They are a constant security hole at times.

Dangling pointers however can be avoided by initializing a NULL pointer value every time we initialize a pointer variable. If in case a programmer assigns a NULL value to a pointer, then it will not point to the memory location that has been freed. By doing so, the pointer will have all the means to not point to any location whatsoever.

Dangling pointers are those pointers whose address it has been pointing in the memory, which is no longer being utilized. It basically points to a value that has been rejected. This leads to errors and bugs that are notoriously hard to debug and due to this very reason, they only cut them at the runtime. Rust provides neat, and elegant solution to the errors by discovering the dangling pointers at the compile time itself and warns the programmer.


Related Topics

Variable Declaration in C

What is a Variable? A Variable is nothing more than a name for a memory place where data/information can be stored. Any alphabet (from a to z or A to Z), the...

4 minutes read.

Find reverse of an array in C using functions

Introduction: Here, we describe how to find the reverse array in C using functions. Suppose you have an array with n elements. I need to display the elements present in...

3 minutes read.

Dynamic memory allocation

Dynamic memory allocation is used to allocate the memory at runtime. It has following function within <stdlib.h> header file. Function Syntax malloc() malloc (number *sizeof(int)); calloc() calloc (number, sizeof(int)); realloc() realloc (pointer_name, number * sizeof(int)); free() free (pointer_name); malloc() function The process...

2 minutes read.

While-Loop in C

Syntax of While Loop The syntax that has been used for the while loop in C programming language is: while (termination condition) {   // the body of the loop  } Working of While-Loop Initially, we...

3 minutes read.

How to use floor() function in C

Introduction: The floor() used as a function in the C programming language. This function uses to return the largest or most significant integer value. The integer value is smaller than...

3 minutes read.

Use of Structure in C

We can usually use arrays in C programming to store elements of the same data type. We can use strings to store multiple elements of a character data type. Still,...

4 minutes read.

Compilation Process in C language

What is the Compilation Process?  The compilation is a method whereby the source code is converted into object code. It is achieved with compiler assistance. The compiler tests the source code for syntactic...

3 minutes read.

C Decision control statement

Decision Making C conditional statements are used to specify one or more conditions. The statements will be executed if the condition becomes true otherwise alternative statement will be executed if the...

3 minutes read.

Java Array vs ArrayList

As we all know, arrays are linear data structures that allow you to add elements to them continuously in memory address space, whereas ArrayList is a Collection framework class. Despite...

4 minutes read.

One Dimensional Array in C

One Dimensional Array in C: In the C programming language, an array is defined as a collection of one or more values of the same type. Every value present in...

4 minutes read.

What is required in each C Program?

Each C program must require one function, i.e., main() function. It is because when we execute the C program, C compiler looks for the main() function, and from here only...

5 minutes read.

Isalnum() function in C

Introduction: The isalnum () is a function used in C programming language. This function checks the passing number or argument is an alphanumeric number or not. The alphanumeric number consists of the...

3 minutes read.

Socket Programming in C

Socket programming is a process that connects the two or more nodes on a networking communication with respective to each other. One of the sockets that determines the socket (I.e.,...

5 minutes read.

Union in C

Union is a user-defined data type that is used to hold the different types of elements like structure. In union, all members share the same memory location. Syntax: union [union name] { ...

1 minute read.

Advantages of Dynamic Memory Allocation in C

Dynamic Memory Allocation Dynamic memory allocation is a process of assigning or allocating memory to a variable during the execution of a program. Dynamic memory allocation provides storage according to the...

3 minutes read.

How to return a Pointer from a Function in C?

In the C programming language, pointers are variables that hold the address memory location of another variable. We could also input pointers to a function and return pointers from a...

3 minutes read.

Function in C

Function is a group of statements that are used to perform any task. In other words, we can say that a function is a self- contained a block of programs...

3 minutes read.

GCD program in C

C language : Dennis Ritchie developed the general-purpose computer language C at Bell Laboratories in 1972. Despite being an ancient language, it is extremely popular. It is among the most widely used...

4 minutes read.

Different ways to Declare the Variable as Constant in C

There are a wide range of ways of making the variable as steady Using const keyword: The const catchphrase permits a software engineer to inform the compiler that a specific variable should...

5 minutes read.

User Defined Functions in C

C Functions: A function is defined as a block of code that is used to perform some specific task. In functions, we use flower brackets ({}) which contain the set of programming...

5 minutes read.