一段C++代码获得"无效指针"错误

nzo*_*xia 0 c++ delete-operator

这是代码:

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
    int *p = new int[2];
    p[0] = 1;
    p[1] = 2;
    cout << *p++ << endl;
    delete p;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

它可以编译,但得到一个运行时错误"free():无效指针",后跟一个内存映射.

操作系统ubuntu 10.10
编译器:g ++ 4.4.3

SLa*_*aks 6

你需要调用以下的数组版本delete:

delete[] p;
Run Code Online (Sandbox Code Playgroud)

编辑:但是,你真正的问题是你正在增加p.
delete运营商只对已分配的原始指针工作.

  • @pyCthon它不是很重要,也不是任何编码的先决条件.[关于此事的讨论](http://stackoverflow.com/questions/1931126/is-it-good-practice-to-null-a-pointer-after-deleting-it). (2认同)