gpt4 book ai didi

c++ - 为什么这个程序不消耗内存?

转载 作者:太空宇宙 更新时间:2023-11-03 10:20:47 25 4
gpt4 key购买 nike

delete [] 的实际作用让我很困扰,所以我只是尝试了一些代码,我对结果感到震惊

测试 #1:

int main()
{
int *d;
while(true)
{
d = new int[10];
delete []d;
}
}

正如预期的那样,该程序根本不消耗任何内存。

测试#2:

int main()
{
int *d;
while(true)
{
d = new int[10];
delete [](d + 5);
}
}

虽然在每个循环中应该至少保留 20 个字节(对于它在数组开头保留的五个整数),这些字节不会被删除,但这个程序也不消耗任何内存!

测试#3:

int main()
{
int *d;
while(true)
{
d = new int[10];
delete []d;
*d=1;
}
}

这导致了预期的访问冲突(似乎在 delete []d 之后所有内存都被删除了)。

测试#4:

int main()
{
int *d;
while(true)
{
d = new int[10];
delete [](d+5);
*d=1;
}
}

这个是最令人惊奇的,虽然它不消耗任何内存程序也不会产生任何访问冲突,但我只是想知道 *d 在哪里存储它的数据?

(顺便说一句,所有程序都是使用无优化编译的!)

现在是主要问题:

如果我分配了一个数组并且我已经完成了一半的工作,我不能有机会释放那一半并保留另一半吗?

最佳答案

it's bothering me what delete [] actually does

您不应该担心 delete[] 实际做了什么。出于所有意图和目的,它都是一个黑匣子,其中包含有关如何正确使用它的某些规则。如果您正在编写编译器或 C++ 运行时(例如操作系统等),您唯一需要担心它实际需要做什么的情况

关于那些“关于如何正确使用它的某些规则”,测试 #2 和 #4 调用未定义的行为:

ISO C++ 2003 Standard 5.3.5 Delete [expr.delete]

1 The delete-expression operator destroys a most derived object (1.8) or array created by a new-expression.

    delete-expression:
::opt delete cast-expression
::opt delete [ ] cast-expression

The first alternative is for non-array objects, and the second is for arrays. The operand shall have a pointer type, or a class type having a single conversion function (12.3.2) to a pointer type. The result has type void.

2 If the operand has a class type, the operand is converted to a pointer type by calling the above-mentioned conversion function, and the converted operand is used in place of the original operand for the remainder of this section. In either alternative, if the value of the operand of delete is the null pointer the operation has no effect. In the first alternative (delete object), the value of the operand of delete shall be a pointer to a non-array object or a pointer to a sub-object (1.8) representing a base class of such an object (clause 10). If not, the behavior is undefined. In the second alternative (delete array), the value of the operand of delete shall be the pointer value which resulted from a previous array new-expression. If not, the behavior is undefined. [Note: this means that the syntax of the delete-expression must match the type of the object allocated by new, not the syntax of the new-expression. ]

“未定义的行为”意味着任何事情都可能发生,包括您刚才描述的行为。

测试 #2 和 #4 中的这些表达式违反了 5.3.5/2,将导致未定义的行为(测试 #3 也会导致未定义的行为,但原因不同)。

d = new int[10];
delete [](d + 5);

delete[] 行违反了 5.3.5/2,因为您传递给 delete[] 的指针值与从 new int[].

因此,如果 new int[] 命令为您提供 0xA01D2CE9 并且您将 0xA01D2CE9 + 5 传递给 delete[],你不可能推理或预测会发生什么,因为你违反了语言规则。实际发生的情况取决于编译器和/或操作系统如何处理 new[]delete[]。范围从没有发生任何错误到系统完全崩溃,以及介于两者之间的任何地方。

换句话说,就是不要写delete [](d + 5);这样的东西。

关于c++ - 为什么这个程序不消耗内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6084137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com