什么是c ++中的悬空指针? [英] What is Dangling pointer in c++?

查看:86
本文介绍了什么是c ++中的悬空指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

c ++中的悬空指针是什么?

解决方案

我想知道维基百科 [ ^ ]。


悬空指针是指向不可用内存位置或无效数据的指针,

例如:



 #include< iostream.h> 
void main(){
int * ptr1;
int * ptr2 = new int ;
ptr1 = ptr2;
删除ptr2;
}





在上面的例子中,ptr1和ptr2指向内存中的相同位置。

但删除了ptr2后。 Ptr1无法指向任何内存。

这称为悬空指针。


  int  * ptr =( int  *)malloc( sizeof  INT )); 
.............
.............
free(ptr);

// ptr现在是一个悬空指针,下面的操作无效
* ptr = 10 ; // 或printf(%d,* ptr);
// 示例2
int * ptr = NULL
{
int x = 10 ;
ptr =& x;
}
// x超出范围,分配给x的内存现在是免费的。
// 所以ptr现在是一个悬空指针。


What is Dangling pointer in c++?

解决方案

I wonder if there is a dedicated page on Wikipedia[^].


A dangling pointer is a pointer that points to the unavailable memory location or data which is not valid,
for eg:

#include<iostream.h>
void main(){
int *ptr1;
int *ptr2 = new int;
ptr1=ptr2;
delete ptr2;
}



In the above example, ptr1 and ptr2 are pointing to the same location in memory.
but after deletion of ptr2. Ptr1 can not able to point any memory.
This is called as dangling pointer.


int *ptr = (int *)malloc(sizeof(int));
.............
.............
free(ptr);

// ptr is a dangling pointer now and operations like following are invalid
*ptr = 10;  // or printf("%d", *ptr);
// EXAMPLE 2
int *ptr = NULL
{
   int x  = 10;
   ptr = &x;
}
// x goes out of scope and memory allocated to x is free now.
// So ptr is a dangling pointer now.


这篇关于什么是c ++中的悬空指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆