// TestApp0828.cpp : Defines the entry point for the console application.
//#include "stdafx.h"
#include <vector>
using namespace std;typedef struct tagInfo { int nlength;
char* p;
}Info;class CInfo
{
public:
int nlength;
char* p;
CInfo()
{
p = NULL;
nlength = 0;
}
virtual ~CInfo()
{
delete []p;
}
protected:
private:
};typedef vector<CInfo> VecInfo;int main(int argc, char* argv[])
{
VecInfo va;
{
CInfo info1;
info1.nlength = 9;
info1.p = new char[9];
memset(info1.p, 0, 9+1);

va.push_back(info1);
CInfo *info2 = &va[0];
}
CInfo info2 = va[0]; printf("Hello World!\n");
return 0;
}

解决方案 »

  1.   

    virtual ~CInfo()
    {
    delete []p; ///出错。 为什么, 
    }
      

  2.   

    if(NULL != p)//最好这样使用
      delete []p;
      

  3.   

    楼上的真是好方法。判断一下是最好的方法。要不都不存在的东西怎么去delete的
      

  4.   

    memset(info1.p, 0, 9+1); 越界了 , 主要是这个。
      

  5.   

    根据ANSI C++的标准,delete NULL是正确的语法,不会出错。主要还是越界的问题。
      

  6.   

    纠正一下,是delete 一个为NULL的指针不会出错,不是delete NULL,呵呵~~~
      

  7.   

    支持楼上的
    delete NULL绝对是没有问题的
    是越界的问题
      

  8.   

    你的代码问题比较多
    1. delete []p; 应该改成delete p
    2. memset(info1.p, 0, 9+1);一共就9个元素,怎么设置时候用10呢
    3. 最主要的问题是你构造了一个对象,然后把它放在vector中,{
    CInfo info1;
    info1.nlength = 9;
    info1.p = new char[9];
    memset(info1.p, 0, 9+1);

    va.push_back(info1);
    CInfo *info2 = &va[0];
    }
    上面这段代码执行完后,会调用CInfo的析构函数
      

  9.   

    在vector被destroy的时候会调用其元素的析构函数,也就是CInfo的析构函数会再被调用一次
      

  10.   

    你的程序应该这样写
    #include "stdafx.h"
    #include <vector>
    using namespace std;typedef struct tagInfo { int nlength;
    char* p;
    }Info;class CInfo
    {
    public:
    int nlength;
    char* p;
    CInfo()
    {
    p = NULL;
    nlength = 0;
    }
    virtual ~CInfo()
    {
    delete p;
    }
    protected:
    private:
    };typedef vector<CInfo*> VecInfo;int main(int argc, char* argv[])
    {
    VecInfo va;
    //{
    CInfo* info1 = new CInfo;
    info1->nlength = 9;
    info1->p = new char[9];
    //memset(info1.p, 0, 9);

    va.push_back(info1);
    // CInfo *info2 = &va[0];
    //}
    CInfo* info2 = va[0]; printf("Hello World!\n");
    return 0;
    }
      

  11.   

    有点问题:
    在程序结束前加上delete info1
      

  12.   

    如果不传指针,而是传对象的引用。
    push_back里面会构造2次对象,其中一次是临时对象。所以在vector被释放的时候,肯定会调用两次析构函数。另外,你自己构造了一个对象,程序结束的时候也会调用它的一次析构,所以析构函数肯定会被调用3次。而这3个对象中的p指向同一个地址,被释放3次肯定有问题。
    3个对象指向同一个地址,是位拷贝引起的