Ani*_*han 137
一个悬摆指针指向的内存已经被释放.不再分配存储空间.尝试访问它可能会导致分段错误.
最终使用悬空指针的常用方法:
char *func()
{
char str[10];
strcpy(str, "Hello!");
return str;
}
//returned pointer points to str which has gone out of scope.
Run Code Online (Sandbox Code Playgroud)
您正在返回一个本地变量的地址,当控制返回到调用函数时,该地址变量将超出范围.(未定义的行为)
另一个常见的悬空指针示例是在该内存上显式调用free之后,通过指针访问内存位置.
int *c = malloc(sizeof(int));
free(c);
*c = 3; //writing to freed location!
Run Code Online (Sandbox Code Playgroud)
一个内存泄漏是一个还没有被释放的内存,就没有办法访问(或免费吧)现在,因为没有办法得到它了.(例如,一个指针,它是对动态分配(并且未释放)的内存位置的唯一引用,现在指向其他位置.)
void func(){
char *ch = malloc(10);
}
//ch not valid outside, no way to access malloc-ed memory
Run Code Online (Sandbox Code Playgroud)
Char-ptr ch是一个局部变量,在函数末尾超出范围,泄漏动态分配的10个字节.
Gre*_*sev 21
您可以将这些视为彼此的对立面.
当你释放一个内存区域,但仍保持指向它的指针时,该指针悬空:
char *c = malloc(16);
free(c);
c[1] = 'a'; //invalid access through dangling pointer!
Run Code Online (Sandbox Code Playgroud)
丢失指针但保留内存分配时,内存泄漏:
void myfunc()
{
char *c = malloc(16);
} //after myfunc returns, the the memory pointed to by c is not freed: leak!
Run Code Online (Sandbox Code Playgroud)
悬挂指针
如果任何指针指向任何变量的内存地址但是在某个变量从该内存位置删除之后指针仍然指向这样的内存位置.这种指针被称为悬空指针,这个问题被称为悬空指针问题.
#include<stdio.h>
int *call();
void main(){
int *ptr;
ptr=call();
fflush(stdin);
printf("%d",*ptr);
}
int * call(){
int x=25;
++x;
return &x;
}
Run Code Online (Sandbox Code Playgroud)
输出:垃圾值
注意:在某些编译器中,您可能会收到返回本地变量或临时地址的警告消息
说明:变量x是局部变量.它的范围和生命周期在函数调用内,因此在返回x变量x的地址变为死并且指针仍然指向ptr仍然指向该位置.
解决这个问题:将变量x作为静态变量.换句话说,我们可以说一个指针对象已被删除的指针称为悬空指针.
内存泄漏
在计算机科学中,当计算机程序错误地管理内存分配时,会发生内存泄漏.按照简单我们已分配内存而不是Free其他语言术语说不释放它调用内存泄漏它对应用程序和意外崩溃是致命的.