删除和无效指针 [英] Delete and invalid pointer

查看:198
本文介绍了删除和无效指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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个问题:


  1. 是否正确的是删除a + 4 只会删除 a + 4 的字符?

  2. 如果对上一个答案是肯定的,那么 a [0] 会发生什么。

  3. 要删除一块内存,我们应该写 delete [] 。但是在这种情况下,所有的元素怎么被删除?

  1. Is it correct that delete a+4 will only delete the character at a+4?
  2. If answer to previous one is yes then what happens to a[0].We should get the output.
  3. 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:


  1. 空指针值。

  2. 以前分配有 new 的完整标量(而不是数组)对象:

    • new
    • 返回的精确指针
    • 指向返回的指针的基本子对象的指针 new 析构函数

    • new ul>
  1. Null pointer values. They simply get ignored.
  2. 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 a virtual destructor

任何这些指针值都不应该传递给标量 delete

Any these pointer values should NEVER ever be passed to scalar delete:


  1. 数组 new new [ ] (使用 delete []

  2. malloc 或不是
  3. 的任何其他分配器
  4. 自动或静态存储持续时间

  5. 成员子对象或数组元素的地址

  6. 未初始化的指针值

  7. 指针指向已删除的对象

  1. The result of array new or new[] (use delete[] instead)
  2. The result of malloc or any other allocator which is not new
  3. The address of an object with automatic or static storage duration
  4. The address of a member subobject or array element
  5. Uninitialized pointer values
  6. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆