我遇到了一个内存越界错误。我就不贴原代码了,我举个例子...
在dll里有这样一个类
class AAA
{
~AAA();//用循环delete掉在vector中的所有指针
void Push(int* NewInt);//向VEC中PUSH_BACK一个指向int的指针
std::vector<int*> VEC;
......
......
}
然后在exe里这样写:
int main()
{
int* var=new int;
AAA* INST=new AAA;
INST.Push(var);
delete INST;
....
....
}
执行那个delette INST的时候就会调用dll中的函数来delete在exe中的数据对吧。现在问题来了:
如果这个dll和exe在同一个solution编译的话,不管debug模式还是release模式,或者exe在debug模式而dll在release模式,都不会出错。
如果dll在一个solution编译,而exe在另一个solution编译,然后在exe里调用这个dll。如果dll是以release模式编译的,而exe以debug编译运行,就会在delete INST的时候出现内存越界错误...
这究竟是怎么回事...
先谢谢大家...

解决方案 »

  1.   

    AAA的析构函数中你是怎么写的
      

  2.   

    std::vector<int*>::iterator Iter=VEC->begin();
    while (Iter!=VEC->end())
    {
    delete *Iter++;
    }
      

  3.   


    这是跨模块分配释放内存造成的
    一般,exe和dll都有自己的heap堆
      

  4.   


    好像这是dll混杂使用造成的问题。
    我搜索了一下看到有这样的介绍:
    If you have an EXE and a DLL.When your exe APP was built Debug Mode, your Dll must be Debug mode. When your exe APP was built Release Mode, your Dll must be Release mode. If exe is Release Mode and Dll is Debug Mode, Error. If exe is Debug Mode and Dll is Release Mode, Error.-------------------------------- Why? --------------------------------Looks like you have a problem with memory allocation.When an application is built in debug mode it does not allocate memory from the same heap as it does in release mode.(have a look to the definition of new and delete operator, and also to malloc (in afxmem.h ? (not sure just grep it))Thus, when you get some memory from your debug app and give this memory to your release dll for processing and FREEING,you get an error since the realase dll tries to free it from the wrong heap. So always use your app and dll in the same mode. At least, do not try to free memory allocation in one mode in the other mode.看来是因为编译方式混杂使用导致的问题。要么都使用release,要么都使用debug,否则在使用dll释放exe内存时就会出现错误。
    结贴散分吧。
      

  5.   

    Exe,DLL本身就希望最好保持一致,Debug或者都是Release