×

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

Sum of N numbers in C using For loop

Before we move on the program of sum of N numbers, first we have to know about the For Loop statement. The syntax of ‘for’ loop in C programming language is...

3 minutes read.

Bar3d() function in C Graphics

The bar3d function is used to create a 2-dimensional filled-in rectangular bar. We can also create three-dimensional shapes in C using helpful function. The first step in creating this 3D...

3 minutes read.

Difference between Array and List in C

C# Array vs List is where the abstraction and implementation of human computing meet.  Arrays are incredibly related to the hardware concept of contiguous and contiguous memory, where each part is...

3 minutes read.

What is a buffer in C?

A buffer is an area of memory set aside for the temporary storage of data. A data buffer (or just buffer) is a region of a physical memory storage used to...

5 minutes read.

Union Program in C

 How should a union be defined?  In C programming, a Union is a method used to organize different data types into groups in the same way that Structures are used. We...

4 minutes read.

GCD program of two numbers in C

GCD stands for Greatest Common Divisor, which is also known as Highest Common Factor, which can be abbreviated as HCF. Mathematically it can be defined as any two positive integers...

3 minutes read.

Types Of Structures In C

We can normally store elements of the same datatype with the help of an array in C programming. We can store multiple numbers of elements of a character data type...

3 minutes read.

How to Avoid Structure Padding in C

Generally, when an object of some structure type is declared, some contiguous memory will be allocated in block form, which will be allocated to structure members. To understand structure padding...

3 minutes read.

Nested Structure in C

In C language, we can create nested Structure (Structure within Structure). There are two ways to define a nested structure. By separate structure By Embedded structure   Separate structure In a separate...

1 minute read.

Library Functions in C

What are library functions? Library functions are the built-in functions (functions provided by the system) which are stored in the library. The library is the common location where these functions are...

3 minutes read.

Data Structures And Algorithms in C

C language is one of the most flexible and simple languages. So, it is always better to learn any concept in C language compared to other languages. Let us look...

13 minutes read.

Fseek Function in C

The fseek function is a function in the C standard library that changes the position of the file pointer in a stream-oriented file. It is typically used to move the...

3 minutes read.

Fibonacci series program in C using Recursion

In this tutorial, we’ll explore how to utilise recursion to build the Fibonacci sequence in C language. What does the term "Fibonacci Series" mean? The following number in a Fibonacci number series is...

2 minutes read.

Difference between Scope and Lifetime in C

In this article, we will discuss about the key differences between scope and lifetime in C, including their definitions, applications, and how they relate to one another. By the end...

8 minutes read.

Big O Notation in C

Big O Notation in C: In the C programming language, we have so many algorithms and solutions to the problems that exist, which have different aspects and purposes to an...

3 minutes read.

Structure Pointer in C

Structure Pointer in C In the C programming language, a structure pointer is defined as a pointer that points to the memory block address that stores a structure. Like C standard...

4 minutes read.

strcat() Function in C

Strings in c: A string is defined as the set of characters that are enclosed within the double quotations (" "). The String always ends with the null character ("\0"). The...

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.

Ceil function in C

Introduction In the C Programming Language, the ceil function is a library function which is used to obtain the ceil value, i.e., it returns the smallest integer that is greater than...

4 minutes read.

fork() in C

Introduction To create a new function in the system, there is a need for a system call, i.e. fork system call. It is also known as the child process. These child...

2 minutes read.