Tutorial Playlist
132 Lessons1. Introduction to C Tutorial
2. Addition of Two Numbers in C
3. Anagram Program in C
4. Armstrong Number in C
5. Array in C
6. Array of Pointers in C
7. Array of Structure in C
8. C Program to Find ASCII Value of a Character
9. Assignment Operator in C
10. Binary Search in C
11. Binary to Decimal in C
12. Bitwise Operators in C
13. Boolean in C
14. C Compiler for Mac
15. C Compiler for Windows
16. C Function Call Stack
17. C Language Download
18. Operators in C
19. C/C++ Preprocessors
20. C Program for Bubble Sort
21. C Program for Factorial
22. C Program for Prime Numbers
23. C Program for String Palindrome
24. C Program to Reverse a Number
25. Reverse a String in C
26. C string declaration
27. String Input Output Functions in C
28. Calculator Program in C
29. Call by Value and Call by Reference in C
30. Ceil Function in C
31. Coding Vs. Programming
32. Command Line Arguments in C/C++
33. Comments in C
34. Compilation process in C
35. Conditional Statements in C
36. Conditional operator in the C
37. Constant Pointer in C
38. Constants in C
39. Dangling Pointer in C
Now Reading
40. Data Structures in C
41. Data Types in C
42. Debugging C Program
43. Convert Decimal to Binary in C
44. Define And include in C
45. Difference Between Arguments And Parameters
46. Difference Between Compiler and Interpreter
47. Difference Between If Else and Switch
48. Do While Loop In C
49. Double In C
50. Dynamic Array in C
51. Dynamic Memory Allocation in C
52. Enumeration (or enum) in C
53. Evaluation of Arithmetic Expression
54. Factorial of A Number in C
55. Features of C Language
56. Fibonacci Series Program in C Using Recursion
57. File Handling in C
58. For Loop in C
59. Format Specifiers in C
60. Functions in C
61. Function Pointer in C
62. goto statement in C
63. C Hello World Program
64. Header Files in C
65. Heap Sort in C Program
66. Hello World Program in C
67. History of C Language
68. How to compile a C program in Linux
69. How to Find a Leap Year Using C Programming
70. Identifiers in C
71. If Else Statement in C
72. If Statement in C
73. Implementation of Queue Using Linked List
74. Increment and decrement operators in c
75. Input and Output Functions in C
76. How To Install C Language In Mac
77. Jump Statements in C
78. Lcm of Two Numbers in C
79. Length of an Array in C
80. Library Function in C
81. Linked list in C
82. Logical Operators in C
83. Macros in C
84. Matrix multiplication in C
85. Nested if else statement in C
86. Nested Loop in C
87. One Dimensional Array in C
88. Operator Precedence and Associativity in C
89. Overflow And Underflow in C
90. Palindrome Program in C
91. Pattern Programs in C
92. Pointer to Pointer in C
93. Pointers in C: A Comprehensive Tutorial
94. Pre-increment And Post-increment
95. Prime Number Program in C
96. Program for Linear Search in C
97. Pseudo-Code In C
98. Random Access Files in C
99. Random Number Generator in C
100. Recursion in C
101. Relational Operators in C
102. Simple interest program in C
103. Square Root in C
104. Stack in C
105. Stack Using Linked List in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
112. String Comparison in C
113. String Functions in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
118. Structure of C Program
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
122. Toupper Function in C
123. Transpose of a Matrix in C
124. Two Dimensional Array in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
129. User Defined Functions in C
130. What is Variables in C
131. Is C language case sensitive
132. Fibonacci Series in C
Dangling pointers refer to the pointers that point to a deallocated memory block. The corresponding condition produces an error called Dangling Pointer Problem. Typically, a dangling pointer comes into the picture when a pointer pointing towards a variable goes out of scope or when a variable’s/object’s memory gets deallocated.
The occurrence of dangling pointers can result in some unforeseen errors during the implementation of a program. Hence, you must avoid them when writing a program.
A dangling pointer in C indicates a pointer pointing to some deleted/freed location from the program's memory. Here the program’s memory refers to the memory that is presently not in the use of the program.
When it comes to dynamic memory allocation, we use calloc(), malloc() functions to allocate a memory block. Moreover, we use the free() function to deallocate a memory block. A dangling pointer is generated after you deallocate a memory block by utilising the free() function.
A dangling pointer in C is generated when we don’t alter the value of a pointer when a variable goes out of scope or after the deallocation of a memory block.
Let’s understand how a dangling pointer works with the help of the below diagram. As seen from the diagram, the memory taken up by the integer variable is deallocated. The pointer ‘ptr’ that points to the deallocated memory now works as a dangling pointer.
The ‘ptr’ is an integer pointer that points to an integer variable with the value 100. It holds the address to the variable. When an integer variable is deallocated from memory, ptr transfers from being a usual pointer to a dangling pointer. Subsequently, it points to some false/not-in-use locations.
There are three ways in which a pointer can work as a dangling pointer in C.
i. Deallocation of memory
ii. Function Call
iii. Variable goes out of scope
Let’s check out the details of each method.
i. Deallocation of memory
The library functions assist in allocating and deallocating memory blocks. The malloc() and calloc() functions are utilised to allocate a memory block, whereas the free() function is used in deallocating a memory block. If you deallocate a memory block through the free() function but don’t alter the value of the pointer, it will result in a dangling pointer. Note that the free() function accepts a single parameter, i.e. a pointer points towards the memory to get deallocated.
Here’s a dangling pointer in C with example that demonstrates the deallocation of memory using the free() function.
// Program that demonstrates dangling pointers using dynamic memory allocation concept
#include <stdio.h> |
The given program uses malloc() to allocate memory for an integer pointer ptr, which is then assigned the value 15. Later, the free() function is used to deallocate the memory block pointed to by ptr, making it a dangling pointer. Accessing the value pointed to by ptr using *ptr in the printf() statement results in undefined behaviour.
ii. Function Call
As you declare a variable within a function, it works as a local variable because it can’t be accessed outside the function’s scope.
Suppose the main() function's pointer holds the address to the particular local variable within the function. Consequently, you can access that local variable’s address until the function’s implementation continues. Once the function execution stops, all internal variables move to garbage collection. They will not exist in memory anymore.
However, the pointer of the main() function still points to that particular address currently not present in memory. So, this scenario creates a dangling condition, and the generated pointer is called a dangling pointer.
Here’s an example program demonstrating dangling pointer in C program using a function call.
#include <stdio.h> |
Output:
Segmentation fault
In the above dangling pointer example, an integer pointer ‘ptr’ is assigned a function call from the danglingPointer() function. This function’s return type is int *. It means that the function will return an address of an integer block which can be stored in an integer pointer.
The danglingPointer() function contains an integer variable var with local scope, and we assigned the value 15 to it. After returning the var variable and the address, the memory being occupied by the danglingPointer() function will be deallocated.
The main() function contains an address saved in the ptr pointer. It points to some deallocated memory which was earlier occupied by var variable. Now ptr works as a dangling pointer since it points to the deallocated memory block.
The output we get is a segmentation fault. This is because the program attempts to access a part of memory that it is not permitted to access.
iii. Variable goes out of scope
A variable declared within an inner block of code has a local scope, which gets destroyed when the execution within the inner block terminates. If we assign a local variable’ address to a pointer which is declared outside of the scope, then it will work as a dangling pointer outside the code block.
Here’s a program that demonstrates using a dangling pointer where a variable goes out of scope.
#include <stdio.h> |
Output:
/tmp/eCpRzkbqQD.o |
Firstly, we declare an integer pointer ‘ptr’ without the initialisation. It is considered a Wild Pointer. The program then defines an integer variable ‘var’ whose scope is until the block’s execution ends. The var’s address is assigned to the ptr pointer.
Suppose the base address is 500, at which the var is allocated. When this block’s scope ends, ptr stays unaffected since it is declared in the external code block. The memory occupied by var is deallocated as it is declared within the block.
Now ptr still holds the address 500. However, nothing exists at this location. It leads to a dangling pointer. The var variable doesn’t exist in the memory, so you can’t alter its value using the ptr pointer.
Avoiding Errors Faced in Dangling Pointer in C
Along with understanding how a dangling pointer works, you must also understand how to avoid dangling pointer in C. You can avoid it either by using static variables (if variables have a local scope) or assigning NULL to the pointer (in case of memory deallocation).
Let’s look at the details of methods to avoid this error.
i. Assign NULL after the deallocation of memory
You must assign NULL to the pointer ptr once the memory block pointed by ptr is deallocated by leveraging the free() function.
ii. Static variables with global scope
Static variables refer to the variables existing in the memory until the program execution continues. You can use the static keyword to declare a static variable which will avoid dangling pointer problems.
Note: You can avoid dangling pointer errors in C by ensuring that the pointer is properly initialised before it is dereferenced.
Dangling pointer in C is helpful when the programmer fails to initialise the pointer with a valid address. Appropriately initialising the pointer will minimise the occurrence of dangling pointers.
Understanding as well as implementing the concept of dangling pointer in C is essential to realise its significance in different scenarios. Following the approach discussed above helps you to curtail the dangling pointer problem.
Along with grasping the fundamentals of C through tutorials, pursuing upGrad’s Executive Post Graduate Programme in Software Development by IIIT-B can prove to be a wise decision for your career advancement! The program imparts you with fundamentals of computer science, the process of building interactive web UI, software development processes, and more, enabling you to bag attractive industry opportunities.
Enroll now to commence your journey!
Q. Is null a dangling pointer?
No, a pointer can’t be dangling and null simultaneously. A null pointer doesn’t point to any memory location, whereas a dangling pointer points to a memory location that has been deallocated.
Q. How do dangling pointers show unpredictable behaviour?
Dangling pointers generate during object destruction, whenever an object which has an incoming reference is deallocated or deleted without altering the value of the pointer. The system might reallocate the earlier freed memory. So, the dangling pointer will show unpredictable behaviour because the memory may now have entirely different data.
Q. What are the differences between a dangling pointer and a void pointer?
A dangling pointer points to a memory location that has been freed or deleted. A void pointer is a specific pointer that points to some data location in storage that doesn’t have any particular type. A dangling pointer points to the deleted object, whereas a void pointer can be assigned the address irrespective of data type.
Q. How do dangling pointers become security holes?
Dangling pointer bugs often become security holes. For instance, if the pointer is utilized to create a virtual function call, a different address may be called because the vtable pointer is overwritten.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...