删除和无效指针 [英] Delete and invalid pointer
问题描述
int main()
{
char* a=new char[20];
cin>>a;
cout<<" character at 7-th position."<<a[6];
delete a+4;
cout<<a[0];
return 0;
}
输入:
1234567894567
输出:
character at 7-th position.6
*** glibc detected *** ./test free() invalid pointer:....
现在我有3个问题:
- 是否正确的是
删除a + 4
只会删除a + 4
的字符? - 如果对上一个答案是肯定的,那么
a [0]
会发生什么。 - 要删除一块内存,我们应该写
delete []
。但是在这种情况下,所有的元素怎么被删除?
- Is it correct that
delete a+4
will only delete the character ata+4
? - If answer to previous one is yes then what happens to
a[0]
.We should get the output. - to delete a chunk of memory we should write
delete[]
.But in this case how come all the elements are deleted?
推荐答案
只有三种类型的指针值可以作为 delete
:
There are only three types of pointer values you can pass as the operand of delete
:
- 空指针值。
- 以前分配有
new
的完整标量(而不是数组)对象:
-
new
返回的精确指针 - 指向返回的指针的基本子对象的指针
new 析构函数
new
ul> -
- Null pointer values. They simply get ignored.
- A complete scalar (not array) object previously allocated with
new
, either of:- The exact pointer returned by
new
- A pointer to a base subobject of the pointer returned by
new
, if and only if the base subobject's type has avirtual
destructor
- The exact pointer returned by
任何这些指针值都不应该传递给标量 delete
:
Any these pointer values should NEVER ever be passed to scalar delete
:
- 数组
new
或new [ ]
(使用delete []
) -
malloc
或不是新
的任何其他分配器 - 自动或静态存储持续时间
- 成员子对象或数组元素的地址
- 未初始化的指针值
- 指针指向已删除的对象
- The result of array
new
ornew[]
(usedelete[]
instead) - The result of
malloc
or any other allocator which is notnew
- The address of an object with automatic or static storage duration
- The address of a member subobject or array element
- Uninitialized pointer values
- Pointers to already-deleted objects
如果违反此规则,您会得到未定义的行为。这意味着您的程序可能崩溃与一个漂亮的消息,检测到无效的删除。或者您的数据可能会损坏,保存在您的数据文件,发送给您的老板,显示给客户,后来你被解雇。
If you break this rule, you get undefined behavior. That means your program might crash with a nice message that an invalid delete was detected. Or your data might get corrupted, saved in your data files, sent to your boss, shown to the customer, and later you get fired. So don't break the rule.
您的代码属于永远不要这个#4类别。
Your code falls into category "NEVER DO THIS #4".
这种方式的原因是因为实现可以(并且大多数)跟踪称为元数据的额外信息以及每个分配的块。例如,块的大小,这对于重用是非常重要的。没有块的一部分的元数据,并且可能没有任何方式从指向中间的指针找到元数据。
The reason it works this way is because an implementation can (and most do) track extra information called metadata along with each allocated block. For example, the size of the block, which is pretty important for enabling reuse. There is no metadata for part of a block, and there may not be any way to find the metadata from a pointer into the middle.
这篇关于删除和无效指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!