C语言 悬空指针和内存泄漏的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13132798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:13:42  来源:igfitidea点击:

Difference between dangling pointer and memory leak

c

提问by dead programmer

I don't understand the difference between a dangling pointer and a memory leak. How are these two terms related?

我不明白悬空指针和内存泄漏之间的区别。这两个术语有什么关系?

回答by Anirudh Ramanathan

A dangling pointerpoints to memory that has already been freed. The storage is no longer allocated. Trying to access it might cause a Segmentation fault.

一个悬摆指针指向的内存已经被释放。不再分配存储。尝试访问它可能会导致分段错误。

Common way to end up with a dangling pointer:

以悬空指针结束的常见方法:

char *func()
{
   char str[10];
   strcpy(str, "Hello!");
   return str; 
}
//returned pointer points to str which has gone out of scope. 

You are returning an address which was a local variable, which would have gone out of scope by the time control was returned to the calling function. (Undefined behaviour)

您正在返回一个地址,它是一个局部变量,当控制返回给调用函数时,该地址将超出范围。(未定义的行为)

Another common dangling pointer example is an access of a memory location via pointer, after free has been explicitlycalled on that memory.

另一个常见的悬空指针示例是通过指针访问内存位置,在该内存上显式调用free 之后。

int *c = malloc(sizeof(int));
free(c);
*c = 3; //writing to freed location!


A memory leakis memory which hasn't been freed, there is no way to access (or free it) now, as there are no ways to get to it anymore. (E.g. a pointer which wasthe only reference to a memory location dynamically allocated(and not freed) which points somewhere else now.)

一个内存泄漏是一个还没有被释放的内存,就没有办法访问(或释放它)现在,因为没有办法得到它了。(例如,一个指针动态分配(而不是释放)的内存位置的唯一引用,它现在指向其他地方。)

void func(){
    char *ch = malloc(10);
}
//ch not valid outside, no way to access malloc-ed memory

Char-ptr ch is a local variable that goes out of scope at the end of the function, leaking the dynamically allocated 10 bytes.

char-ptr ch 是一个局部变量,在函数结束时超出范围,泄漏动态分配的10 bytes

回答by Greg Inozemtsev

You can think of these as the opposites of one another.

您可以将它们视为彼此的对立面。

When you free an area of memory, but still keep a pointer to it, that pointer is dangling:

当您释放内存区域,但仍保留指向它的指针时,该指针悬空:

char *c = malloc(16);
free(c);
c[1] = 'a'; //invalid access through dangling pointer!

When you lose the pointer, but keep the memory allocated, you have a memory leak:

当您丢失指针但保留分配的内存时,您会发生内存泄漏:

void myfunc()
{
    char *c = malloc(16);
} //after myfunc returns, the the memory pointed to by c is not freed: leak!

回答by maerics

A dangling pointeris one that has a value (not NULL) which refers to some memory which is not valid for the type of object you expect. For example if you set a pointer to an object then overwrote that memory with something else unrelated or freed the memory if it was dynamically allocated.

悬挂指针是一个具有的值(不为空),这是指一些存储器,它是无效的您期望的对象的类型。例如,如果您设置一个指向对象的指针,然后用其他不相关的东西覆盖该内存,或者如果它是动态分配的,则释放该内存。

A memory leakis when you dynamically allocate memory from the heap but never free it, possibly because you lost all references to it.

一个内存泄漏是当你动态地从堆中分配内存,但永远不会释放它,可能是因为你失去了对它的所有引用。

They are related in that they are both situations relating to mismanaged pointers, especially regarding dynamically allocated memory. In one situation (dangling pointer) you have likely freed the memory but tried to reference it afterwards; in the other (memory leak), you have forgotten to free the memory entirely!

它们是相关的,因为它们都是与管理不当的指针有关的情况,特别是关于动态分配的内存。在一种情况下(悬空指针),您可能已经释放了内存,但之后尝试引用它;在另一个(内存泄漏)中,您忘记了完全释放内存!

回答by PeterParker

Dangling Pointer

悬空指针

If any pointer is pointing the memory address of any variable but after some variable has deleted from that memory location while pointer is still pointing such memory location. Such pointer is known as dangling pointerand this problem is known as dangling pointer problem.

如果任何指针指向任何变量的内存地址,但在某个变量从该内存位置删除后,而指针仍指向该内存位置。这种指针被称为悬垂指针,这个问题被称为悬垂指针问题。

#include<stdio.h>

  int *call();

  void main(){

      int *ptr;
      ptr=call();

      fflush(stdin);
      printf("%d",*ptr);

   }

 int * call(){

   int x=25;
   ++x;
   return &x;
 }

Output: Garbage value

输出:垃圾值

Note: In some compiler you may get warning message returning address of local variable or temporary

注意:在某些编译器中,您可能会收到警告消息,返回局部变量或临时变量的地址

Explanation: variable x is local variable. Its scope and lifetime is within the function call hence after returning address of x variable x became dead and pointer is still pointing ptr is still pointing to that location.

解释:变量 x 是局部变量。它的范围和生命周期在函数调用内,因此在返回 x 变量的地址后 x 变为死,指针仍然指向 ptr 仍然指向该位置。

Solution of this problem: Make the variable x is as static variable. In other word we can say a pointer whose pointing object has been deleted is called dangling pointer.

此问题的解决方案:将变量 x 设为静态变量。换句话说,我们可以说一个指向对象已被删除的指针称为悬空指针。

Memory Leak

内存泄漏

In computer science, a memory leak occurs when a computer program incorrectly manages memory allocations. As per simple we have allocated the memory and not Free other language term say not release it call memory leak it is fatal to application and unexpected crash.

在计算机科学中,当计算机程序错误地管理内存分配时会发生内存泄漏。简单地说,我们分配了内存而不是 Free 其他语言术语说不释放它称为内存泄漏,它对应用程序和意外崩溃是致命的。

回答by rashok

Pointer helps to create user defined scope to a variable, which is called Dynamic variable. Dynamic Variable can be single variable or group of variable of same type (array) or group of variable of different types (struct). Default local variable scope starts when control enters into a function and ends when control comes out of that function. Default global vairable scope starts at program execution and ends once program finishes.

指针有助于创建用户定义的变量范围,称为动态变量。动态变量可以是单个变量或一组相同类型的变量 ( array) 或一组不同类型的变量 ( struct)。默认局部变量作用域在控制进入函数时开始,在控制离开该函数时结束。默认全局变量作用域在程序执行时开始,并在程序完成后结束。

But scope of a dynamic variable which holds by a pointer can start and end at any point in a program execution, which has to be decided by a programmer. Dangling and memory leak comes into picture only if a programmer doesnt handle the end of scope.

但是由指针保存的动态变量的范围可以在程序执行的任何一点开始和结束,这必须由程序员决定。只有当程序员不处理作用域结束时,才会出现悬空和内存泄漏。

Memory leak will occur if a programmer, doesnt write the code (freeof pointer) for end of scope for dynamic variables. Any way once program exits complete process memory will be freed, at that time this leaked memory also will get freed. But it will cause a very serious problem for a process which is running long time.

如果程序员没有free为动态变量的作用域结束编写代码(指针),则会发生内存泄漏。无论如何,一旦程序退出完整进程内存将被释放,届时这部分泄漏的内存也将被释放。但是对于长时间运行的进程来说,会造成非常严重的问题。

Once scope of dynamic variable comes to end(freed), NULLshould be assigned to pointer variable. Otherwise if the code wrongly accesses it undefined behaviour will happen. So dangling pointer is nothing but a pointer which is pointing a dynamic variable whose scope is already finished.

一旦动态变量的作用域结束(释放),就NULL应该分配给指针变量。否则,如果代码错误地访问它,就会发生未定义的行为。所以悬空指针只不过是一个指针,它指向一个作用域已经结束的动态变量。

回答by user2264571

Memory leak: When there is a memory area in a heap but no variable in the stack pointing to that memory.

内存泄漏:当堆中有内存区域但堆栈中没有指向该内存的变量时。

char *myarea=(char *)malloc(10);

char *newarea=(char *)malloc(10);

myarea=newarea;

Dangling pointer: When a pointer variable in a stack but no memory in heap.

悬空指针:当指针变量在堆栈中但堆中没有内存时。

char *p =NULL;

A dangling pointer trying to dereference without allocating space will result in a segmentation fault.

尝试取消引用而不分配空间的悬空指针将导致分段错误。

回答by Niravdas

A pointer pointing to a memory location that has been deleted (or freed) is called dangling pointer.

指向已被删除(或释放)的内存位置的指针称为悬空指针。

#include <stdlib.h>
#include <stdio.h> 
 void  main()
 {
    int *ptr = (int *)malloc(sizeof(int));
    // After below free call, ptr becomes a 
    // dangling pointer
    free(ptr); 
 }

for more information click HERE

了解更多信息,请点击这里

回答by Lalit

A pointer pointing to a memory location that has been deleted (or freed) is called dangling pointer. There are three different ways where Pointer acts as dangling pointer.

  1. De-allocation of memory
  2. Function Call
  3. Variable goes out of scope

指向已被删除(或释放)的内存位置的指针称为悬空指针。Pointer 可以通过三种不同的方式充当悬空指针。

  1. 取消分配内存
  2. 函数调用
  3. 变量超出范围

—— from https://www.geeksforgeeks.org/dangling-void-null-wild-pointers/

——来自https://www.geeksforgeeks.org/dangling-void-null-wild-pointers/