这是代码:

#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;
}


可以编译它,但出现运行时错误“ free():无效的指针”,然后显示内存映射。

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

最佳答案

您需要调用delete的数组版本:

delete[] p;


编辑:但是,您的真正问题是您要递增p
delete运算符仅对分配的原始指针起作用。

关于c++ - 一段C++代码获取“无效指针”错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12232859/

10-11 22:23
查看更多