×

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

Palindrome Number in C

What is a Palindrome? A number that doesn't change when reversed is known as a palindrome. We reverse a number and compare it to the original number to determine whether it is...

4 minutes read.

Escape Sequence in C

An escape sequence is a sequence of character that used inside the string literal or character.  All the escape sequence is used with the backslash (\) symbol. The list of an...

1 minute read.

What is the main in C?

In the C programming language, "main" is a predefined term or function. It is the primary function in every C program and is in charge of beginning and terminating the...

6 minutes read.

Tower of Hanoi in C

What is Tower of Hanoi? The Tower of Hanoi is a gaming problem that was created in 1883 by a French mathematician named Édouard Lucas. The Tower of Hanoi temple in...

4 minutes read.

Factorial Program in C Using While Loop

Before looking into the mechanism of factorial program, first, you have to understand about the working of a while loop. While Loop The syntax that has been used for the “while” loop...

4 minutes read.

Use of free() function in C

Introduction The free() function uses in C programming language. The free() function in the C programming language uses to release or deallocate the memory blocks; these blocks are previously allocated by calloc(), malloc() or realloc()...

3 minutes read.

Data Types in C

Data type is a very important concept in C programming language. Simply, “A data type is the classification of data values that a data item can have.” We need to...

11 minutes read.

Beep() function in C

Introduction: Beep is a function which is used in C programming language. The beep function uses to make a beep sound. In the C language, when we want to generate...

3 minutes read.

Ferror() in c

Ferror():  In C, the ferror() function checks assuming there is a blunder in the given stream. The ferror() function is utilized to check for the document blunder on given stream. A return...

4 minutes read.

C/C++ Program to Find the Size of int, float, double and char

In this tutorial, we will learn how to use the sizeof operator to determine the size of each variable. Program to Determine Variable Size Write a C or C++ program to determine the...

2 minutes read.

Conditional Operator in C

In C programming language, the conditional operator (also known as the ternary operator) is a shorthand way of writing an if-else statement. The syntax of conditional operator in C is...

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.

Floyd’s triangle in C

Floyd’s triangle in C Floyd’s triangle is named after a person Robert Floyd. It is a right-angled triangle that is of natural numbers starting from 1 and consecutively selects the upcoming...

4 minutes read.

fgets() function in C

fgets() function is present in standard input and output library i.e, stdio.h library. It is a built-in function or pre-define function. It is used to read the specified stream from...

4 minutes read.

Integer Promotions in C

As we know that some of the data types such as char, short int, Enum takes a smaller number of bytes than compared to int. When an operation is applied...

3 minutes read.

Multi-dimensional Arrays in C

Multi-dimensional Arrays in C The C programming allows the concept of multi-dimensional arrays. The data within the multidimensional arrays are stored in the tabular form, that is, in a row significant...

3 minutes read.

C and C++ Binary Files

What is a binary file? A file in which the content is written in binary format is called a binary file. A binary file is not a text file. There are...

7 minutes read.

C program to Store Information of Students Using Structure

What is the Structure in C? User-defined data types include structures. Structures aid your ability to combine things of various categories into a single group. Like arrays, it operates similarly. A...

3 minutes read.

Multithreading in C interview questions

Q1. What exactly is a thread? Ans: A thread is a brief sequence of instructions intended to be planned and carried out by the CPU apart from the parent process. Q2. Can...

4 minutes read.

Builtin functions of GCC compiler

Certain built-in functions are present in the GCC compiler. These features are as follows: Function_ built in_popcount (x) The number of 1s in data of the integer type can be counted using...

3 minutes read.