- C Programming Tutorial
- C - Home
- Basics of C
- C - Overview
- C - Features
- C - History
- C - Environment Setup
- C - Program Structure
- C - Hello World
- C - Compilation Process
- C - Comments
- C - Tokens
- C - Keywords
- C - Identifiers
- C - User Input
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Integer Promotions
- C - Type Conversion
- C - Type Casting
- C - Booleans
- Constants and Literals in C
- C - Constants
- C - Literals
- C - Escape sequences
- C - Format Specifiers
- Operators in C
- C - Operators
- C - Arithmetic Operators
- C - Relational Operators
- C - Logical Operators
- C - Bitwise Operators
- C - Assignment Operators
- C - Unary Operators
- C - Increment and Decrement Operators
- C - Ternary Operator
- C - sizeof Operator
- C - Operator Precedence
- C - Misc Operators
- Decision Making in C
- C - Decision Making
- C - if statement
- C - if...else statement
- C - nested if statements
- C - switch statement
- C - nested switch statements
- Loops in C
- C - Loops
- C - While loop
- C - For loop
- C - Do...while loop
- C - Nested loop
- C - Infinite loop
- C - Break Statement
- C - Continue Statement
- C - goto Statement
- Functions in C
- C - Functions
- 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
- 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
- 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 - Passing Pointers to Functions
- C - Return Pointer from Functions
- C - Function Pointers
- C - Pointer to an Array
- C - Pointers to Structures
- C - Chain of Pointers
- C - Pointer vs Array
- C - Character Pointers and Functions
- C - NULL Pointer
- C - void Pointer
- C - Dangling Pointers
- C - Dereference Pointer
- C - Near, Far and Huge Pointers
- C - Initialization of Pointer Arrays
- C - Pointers vs. Multi-dimensional Arrays
- Strings in C
- C - Strings
- C - Array of Strings
- C - Special Characters
- C Structures and Unions
- C - Structures
- C - Structures and Functions
- C - Arrays of Structures
- C - Self-Referential Structures
- C - Lookup Tables
- C - Dot (.) Operator
- C - Enumeration (or enum)
- C - Structure Padding and Packing
- C - Nested Structures
- C - Anonymous Structure and Union
- C - Unions
- C - Bit Fields
- C - Typedef
- File Handling in C
- C - Input & Output
- C - File I/O (File Handling)
- C Preprocessors
- C - Preprocessors
- C - Pragmas
- C - Preprocessor Operators
- C - Macros
- C - Header Files
- Memory Management in C
- C - Memory Management
- C - Memory Address
- C - Storage Classes
- 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
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 doesn’t 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.