
- C - Home
- C - Overview
- C - Features
- C - History
- C - Standards
- C - Environment Setup
- C - Program Structure
- C - Hello World
- C - Compilation Process
- C - Comments
- C - Basic Syntax
- C - User Input
- C - printf Function
- C - Format Specifiers
- Lexical Elements in C
- C - Tokens
- C - Keywords
- C - Identifiers
- Variables and Constants
- C - Variables
- C - Constants
- C - Const Qualifier
- C - Linkage
- Data Types and Type Conversions
- C - Data Types
- C - Literals
- C - Escape sequences
- C - Booleans
- C - Integer Promotions
- C - Character Arithmetic
- C - Type Conversion
- C - Type Casting
- Operators in C
- C - Operators
- C - Arithmetic Operators
- C - Unary Operators
- C - Relational Operators
- C - Logical Operators
- C - Bitwise Operators
- C - Assignment Operators
- C - Increment and Decrement Operators
- C - Ternary Operator
- C - sizeof Operator
- C - Operator Precedence
- C - Miscellaneous Operators
- Decision Making & Control Statements
- C - Decision Making
- C - if statement
- C - if...else statement
- C - if...else if Ladder
- C - Nested if statements
- C - Switch statement
- C - Nested switch statements
- C - Switch Case Using Range
- Loops in C
- C - Loops
- C - For Loop
- C - While Loop
- C - Do...while Loop
- C - For Loop vs While Loop
- C - Nested Loop
- C - Infinite Loop
- C - Break Statement
- C - Continue Statement
- C - Goto Statement
- Functions in C
- C - Functions
- C - Function Prototype
- C - Main Function
- C - Function call by Value
- C - Function call by reference
- C - Nested Functions
- C - Variadic Functions
- C - User-Defined Functions
- C - Callback Function
- C - Return Statement
- C - Recursion
- C - Predefined Identifier __func__
- Scope Rules in C
- C - Scope Rules
- C - Static Variables
- C - Global Variables
- Arrays in C
- C - Arrays
- C - Properties of Array
- C - Multi-Dimensional Arrays
- C - Passing Arrays to Function
- C - Return Array from Function
- C - Variable Length Arrays
- C - Dynamic Arrays
- Strings in C
- C - Strings
- C - Array of Strings
- C - Character Arrays
- C - Special Characters
- Structures and Unions in C
- C - Structures
- C - Structures and Functions
- C - Arrays of Structures
- C - Self-Referential Structures
- C - Dot (.) Operator
- C - Lookup Tables
- C - Enumeration (or enum)
- C - Structure Padding and Packing
- C - Nested Structures
- C - Anonymous Structure and Union
- C - Unions
- C - Bit Fields
- C - Typedef
- Pointers in C
- C - Pointers
- C - Pointers and Arrays
- C - Applications of Pointers
- C - Pointer Arithmetics
- C - Array of Pointers
- C - Pointer to Pointer
- C - Function Pointers
- C - Array of Function Pointers
- C - Passing Pointers to Functions
- C - Return Pointer from Functions
- C - Pointer to an Array
- C - Pointers vs. Multi-dimensional Arrays
- C - Character Pointers and Functions
- C - NULL Pointer
- C - void Pointer
- C - Const Pointers & Pointer to Const
- C - Dangling Pointers
- C - Dereference Pointer
- C - Near, Far and Huge Pointers
- C - Restrict Keyword
- C - Pointers to Structures
- C - Chain of Pointers
- C - Pointer vs Array
- C - Initialization of Pointer Arrays
- Storage Classes and Qualifiers
- C - Storage Classes
- Memory Management in C
- C - Memory Management
- C - Memory Address
- Preprocessors in C
- C - Preprocessors
- C - Pragmas
- C - Preprocessor Operators
- File Handling in C
- C - File I/O (File Handling)
- C - Input & Output
- Constants and Literals in C
- C - Macros
- C - Header Files
- Miscellaneous Topics
- C - Error Handling
- C - Variable Arguments
- C - Command Execution
- C - Math Functions
- C - Static Keyword
- C - Random Number Generation
- C - Command Line Arguments
- C Programming Resources
- C - Questions & Answers
- C - Quick Guide
- C - Cheat Sheet
- C - Useful Resources
- C - Discussion
- C Online Compiler
Dangling Pointers in C
Dangling Pointers in C
Dangling pointers in C is used to describe the behavior of a pointer when its target (the variable it is pointing to) has been deallocated or is no longer accessible. In other words, a dangling pointer in C is a pointer that doesn't point to a valid variable of the appropriate type.
Why Do We Get Dangling Pointers in C?
Working with a dangling pointer can lead to unpredicted behavior in a C program and sometimes it may result in the program crashing. The situation of dangling pointers can occur due to the following reasons −
- De-allocation of memory
- Accessing an out-of-bounds memory location
- When a variable goes out of scope
Let's analyze each of these three situations with the help of examples.
De-allocation of Memory
A pointer holds the address of a variable. If the target variable is deallocated or freed, then its pointer becomes a dangling pointer. Trying to access a pointer whose target variable has been deallocated results in garbage situations.
Let us use malloc() to create an integer variable and store its address in an integer pointer.
int *x = (int *) malloc(sizeof(int)); *x = 100;
Here, the pointer is referring to a valid location in the memory. Let us release the memory pointed by "x" using the free() function.
free(x);
Now, "x" stores an address that is no longer valid. Hence, if we try to dereference it, the compiler shows a certain garbage value.
Example
The following example shows how we end up getting dangling pointers in a C program −
#include <stdio.h> int main(){ int *x = (int *) malloc(sizeof(int)); *x = 100; printf("x: %d\n", *x); free (x); printf("x: %d\n", *x); }
Output
Run the code and check its output −
x: 100 x: 11665744
Accessing an Out-of-Bounds Memory Location
We know that a function can return a pointer. If it returns a pointer to any local variable inside the function, it results in a dangling pointer in the outer scope, as the location it points to is no longer valid.
Example
Take a look at the following code −
#include <stdio.h> int * function(); int main(){ int *x = function(); printf("x: %d", *x); return 0; } int * function(){ int a =100; return &a; }
Output
When compiled, the following warning is displayed at the "return &a" statement in the function −
warning: function returns address of local variable [-Wreturn-local-addr]
If you run the program despite the warning, you get the following error −
Segmentation fault (core dumped)
When you get this error, it means that the program is trying to access a memory location that is out of bounds.
When a Variable Goes Out of Scope
The same reason applies when a variable declared in an inner block is accessed outside it. In the following example, we have a variable inside a block and its address is stored in a pointer variable.
However, outside the block, the pointer becomes a dangling pointer as its target is out of bounds.
Example
The following program shows how we get a dangling pointer when its base variable goes out of scope −
#include <stdio.h> int main(){ int *ptr;{ int a = 10; ptr = &a; } // 'a' is now out of scope // ptr is a dangling pointer now printf("%d", ptr); return 0; }
Output
It will display a garbage value −
6422036
How to Fix Dangling Pointers?
C doesnt have the feature of automatic garbage collection, so we need to carefully manage the dynamically allocated memory.
To fix the issue of dangling pointers or to avoid them altogether, you need to apply proper memory management and try to avoid situations where you may end up getting dangling pointers.
Here are some general guidelines that you can follow to avoid dangling pointers −
- Always ensure that pointers are set to NULL after the memory is deallocated. It will clearly signify that the pointer is no longer pointing to a valid memory location.
- Avoid accessing a variable or a memory location that has gone out of scope.
- Do not return pointers to local variables because such local variables will go out of scope when the function returns.
By following these guidelines, you can reduce the chances of getting dangling pointers in your code.