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

推荐答案

A dangling pointer points 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 explicitly called on that memory.

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

A memory leak is 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 was the 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.

C++相关问答推荐

Mise()在虚拟内存中做什么?

由Go调用E.C.引起的内存快速增长

为什么GCC在每次循环迭代时都会生成一个数组的mov&S使用[]访问数组?(-03,x86)

为什么我一直收到分段错误?

N的值设置为0或1(未定义的行为),而我正在try 学习realloc和Malloc的用法

是什么让numpy.sum比优化的(自动矢量化的)C循环更快?

接受任何参数的函数指针是否与接受不同参数的函数兼容

为什么GCC-O1优化破解了这个代码,为了一个GameBoy高级只读存储器而修改了VRAM的循环?

从不兼容的指针类型返回&&警告,但我看不出原因

Realloc():中止的下一个大小无效(核心转储)

表达式x&;&;(~x)应该返回1还是0?它依赖于编译器吗?

当读取可能会阻塞管道中的父进程时,为什么要等待子进程?

通过GTK';传递回调参数;s g_signal_connect()导致C中出现意外值

函数的typedef是标准 C 语法吗?它与函数指针的typedef有何不同?

为什么写入关闭管道会返回成功

与 C 相比,C++ 中无副作用的无限循环的好处是 UB?

在 C/C++ 中原子按位与字节的最佳方法?

设置具有非零终止字符串的大整数

CS50多项,印刷优胜者

在k个簇中找到集合划分的最小平方和