×

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

Int in C

The keyword int in C programming stands for integer and it is a data type which is used for variable declarations or declaration of functions of different types. Similar to...

4 minutes read.

C Switch Statements

Switch-case statement comes under the Selection control statement; there are four types of Control statements Decision-making statements (if, if-else)Selection statements (Switch-case)Iteration statements (for, while, do-while)Jump statements (break, continue, goto) If we want...

4 minutes read.

SJF Scheduling Program in C

The SJF (shortest job first) or the shortest job next is the programming scheduling in the C. It is one of the CPU scheduling programming. The SJF is defined as...

4 minutes read.

C Program to find the Roots of a Quadratic Equation

What is Quadratic Equation: Equations of degree 2 in polynomial form are called quadratic equations. A, B, and C are the coefficient variables in the equation, which is written as ax2...

3 minutes read.

C Programming Tutorial

What is C Programming C is most popular and widely used computer programming language. It was developed by Dennis Ritchie in 1972 at the Bell Lab. It is used to develop system application software. There...

8 minutes read.

#error #pragma in C

#error, #pragma in C #error, also known as the error directive in the C language. It will not allow you to make any compilation fail and immediately issues a statement which...

4 minutes read.

Derived Data Types in C

A variable in a program occupies some space in the computer's memory where some value is stored. Each variable in C has an associated data type. A value to be...

4 minutes read.

What are linker and loader in C

Linker and loader are utility programs that have a significant role in executing a program. Linker: A linker is a program that joins the object files produced by the assembler/ compiler...

3 minutes read.

10 Best IDEs for C or C++ Developers in 2024

Nobody can deny the fact that C and C++ were the first programming languages used by significant developers worldwide. Even now, newcomers who want to start programming are most frequently...

6 minutes read.

Find occurrence of substring in C using function

Introduction: In this article, we discuss finding the occurrence of a substring in C using function. This software takes strings and substrings as input and counts the occurrences of substrings within...

3 minutes read.

Self-referential structure in C

Self-referential structure in C A self-referential structure is a structure that can have members which point to a structure variable of the same type. They can have one or more pointers...

3 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.

C program that does not Suspend when Ctrl+Z is Pressed

In Programming when a program breakdown and runs surprisingly in the terminal compiler the developer has the ability to prevent the program from running unequivocally. For expressly halting the program,...

3 minutes read.

Comma Operator in C

What is a comma operator? The comma operator in the C programming language has the least priority. The comma operator is essentially a binary operator that operates on the first operand...

4 minutes read.

How to use Typedef Struct in C

The “typedef” is a predefined keyword in C programming language which is used to declare the new name to an existing type of variable. For better understanding, if you declare a...

3 minutes read.

How to Calculate Time Complexity in C?

What is time complexity? An algorithm's time complexity measures how long it takes to complete a task in relation to the size of the input. It should be noted that the...

5 minutes read.

Flexible Array Members in a Structure in C

There is flexibility to declare array from c99 generation onwards that declaration of the collections can be made possible without even mentioning its dimension, which means that the displays are...

4 minutes read.

Loop Questions in C

Question 1: What is For loop syntax? Ans: The syntax that has been used for the ‘for’ loop in C programming language is: for (initialization statement /*for providing a value to variables*/; test...

19 minutes read.

How to use atoi() function in C

Introduction: The atoi() is a function used in C programming language. This function converts string characters to the integer value. The atoi() function converts the input string to the return type of...

4 minutes read.

Simple Programs in C Language

In this article, we will discuss the basic programs in C language. Addition of two values in C. Swapping two values. Finding the odd or even values. Finding vowels and consonants in C. Finding the...

11 minutes read.