Ver*_*era 4 c++ pointers memory-leaks
我很难理解如何分辨悬空指针和内存泄漏.关于最近的任务令我感到困惑,我有几个问题,在阅读之后,我仍然感到困惑.我不希望有人为我做我的作业,我希望能够理解为什么它是什么,如果这是有道理的.
所以,作业:
鉴于声明:
int *ptrA, *ptrB;
Run Code Online (Sandbox Code Playgroud)
判断下面的每个代码段是否导致内存泄漏,悬空指针或两者都没有.画画帮忙.
ptrA已经指向内存中的东西,所以这个既不是悬空指针也不是内存泄漏.ptrA = new int;
ptrB = new int;
*ptrA = 345;
ptrB = ptrA;
Run Code Online (Sandbox Code Playgroud)
ptrB没有任何结果.ptrA = new int;
*ptrA = 345;
ptrB = ptrA;
delete ptrA;
Run Code Online (Sandbox Code Playgroud)
ptrA = new int;
ptrB = new int;
*ptrA = 345;
*ptrB = *ptrA;
Run Code Online (Sandbox Code Playgroud)
ptrA = new int;
ptrB = new int;
*ptrA = 345;
ptrB = new int;
*ptrB = *ptrA;
Run Code Online (Sandbox Code Playgroud)
ptrA = LocationOfAge();
Run Code Online (Sandbox Code Playgroud)
其中函数LocationOfAge定义为:
int *LocationOfAge() {
int age = 21;
return &age;
}
Run Code Online (Sandbox Code Playgroud)
感谢愿意提供帮助的任何人.
Mar*_*ork 12
游戏规则:
new Type抽一个盒子.在框中提出一个问题(你不知道那里有什么).delete p指向的每个交叉方向p.a = b(没有星星的地方)从变量a到框画一条线b.*x = y写入.yx*x = *y读取盒子的内容y并放入副本x结果:
第一个问题:
ptrA = new int;
ptrB = new int;
*ptrA = 345;
ptrB = ptrA;
Run Code Online (Sandbox Code Playgroud)
让我们一行一行:
ptrA = new int;
// Part 1 has a new so draw a box
*********
* ? *
*********
// Part 2 assignment to variable add a line
ptrA -------> *********
* ? *
*********
Run Code Online (Sandbox Code Playgroud)
ptrB = new int;
// Part 3 has a new so draw another box
ptrA -------> *********
* ? *
*********
*********
* ? *
*********
// Part 4 assignment to variable add a line
ptrA -------> *********
* ? *
*********
ptrB -------> *********
* ? *
*********
Run Code Online (Sandbox Code Playgroud)
*ptrA = 345;
ptrA -------> *********
* 345 *
*********
ptrB -------> *********
* ? *
*********
Run Code Online (Sandbox Code Playgroud)
ptrB = ptrA;
ptrA -------> *********
| * 345 *
| *********
|
ptrB ---- *********
* ? *
*********
Run Code Online (Sandbox Code Playgroud)
好像你有一个泄漏的盒子.即有一个没有变量指向它的框.