Cprogramming 简明教程
Dangling Pointers in C
Dangling Pointers in C
C 中的 Dangling pointers 用于描述 pointer 当其目标(它指向的变量)已释放或不再可以访问时的行为。换句话说,C 中的 dangling pointer 是一个不指向适当类型的有效变量的指针。
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?
使用悬空指针在 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
指针持有 variable 的地址。如果目标变量被释放,则其指针将成为悬空指针。尝试访问其目标变量已释放的指针会导致垃圾情况。
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.
让我们使用 malloc() 创建一个整数变量并在整数指针中存储它的地址。
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;
此处,指针引用内存中的一个有效位置。让我们使用 free() 函数释放 "x" 指向的内存。
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);
现在,“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
以下示例展示了如何在 C 程序中得到悬空指针:
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);
}
运行代码并检查其输出:
Run the code and check its output −
x: 100
x: 11665744
Accessing an Out-of-Bounds Memory Location
我们知道 function 可以返回指针。如果它返回函数内部任何局部变量的指针,它会导致外部范围中出现悬空指针,因为它所指向的位置不再有效。
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;
}
编译时,以下 warning 将显示在函数中的“return &a”语句中:
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]
如果你在有警告的情况下运行程序,你将得到以下 error :
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;
}
它将显示垃圾值:
It will display a garbage value −
6422036
How to Fix Dangling Pointers?
C 并没有自动垃圾回收功能,因此我们需要仔细管理动态分配的内存。
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.
以下是你可以在避免悬空指针时遵循的一些 general guidelines :
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.