我写了一个分配二维数组的函数,如下:template<class T>T** malloc_2dim_mat(int dim1, int dim2)
{
T** mat;
int i;
try{
mat = (T**)new T*[dim1];
}
catch(exception& ex){
cout << ex.what() << endl;
}
for(i=0;i<dim1;i++){
try{
mat[i] = (T*)new T[dim2];
}
catch(exception& ex){
cout << ex.what() << endl;
}
} return mat;
}在为一个二维double指针分配内存(大小为95×36个double数)时,为mat分配内存成功,但为mat[0]分配内存时引发了一个异常,经跟踪发现是operator new调用了若干层函数后最好调用API函数HeapAlloc时引发的。但是HeapAlloc刚一返回该异常就被处理了,不知是谁处理的,因为跟踪到HeapAlloc内部后只看到一堆汇编代码,看不明白。现在想搞清楚的是不是因为堆中的内存不够或者别的什么原因导致内存分配失败呢?查了一下API函数,好像没发现能返回堆中相关信息的函数(比如堆有多大,还有多少剩余空间,等等。也不知我对堆的理解对不对,呵呵),只有能返回堆中内存块信息的函数(比如HeapWalk)。不知我的想法对不对,请大侠指教!谢谢!

解决方案 »

  1.   

    把你的代码发给我看看?
    [email protected]
      

  2.   

    多谢帮助!代码已经发给你了。我的QQ:626688。MSN:[email protected]。最好能在线交流!
      

  3.   

    多谢几位大侠!原来的代码好像有问题,现改为用SEH处理异常。仍然无法捕获异常。请大侠继续指点迷津,小弟感激不尽!long ExceptionFilter(DWORD dwExceptionCode, LPEXCEPTION_POINTERS lpExceptionPointers)
    {
    return dwExceptionCode == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
    }template<class T>T** malloc_2dim_mat(int dim1, int dim2)
    {
    T** mat;
    int i;
    if((mat = (T**)new T*[dim1]) == NULL){
    MessageBox(NULL, "Failed to allocate memory for 2 dimensional T matrix!", "Error!", MB_OK | MB_ICONWARNING | MB_DEFBUTTON1);
    return NULL;
    }
    for(i=0;i<dim1;i++){
    // SEH try block
    __try{
    mat[i] = (T*)new T[dim2];
    }
    __except(ExceptionFilter(GetExceptionCode(), GetExceptionInformation())){
    cout << "Exceptions happened!\n";
    }
    // C++ try block
    } return mat;
    }
      

  4.   

    If there is insufficient memory for the allocation request, by default operator new returns NULL. You can change this default behavior by writing a custom exception-handling routine and calling the _set_new_handler run-time library function with your function name as its argument.
      

  5.   

    "是不是因为堆中的内存不够或者别的什么原因导致内存分配失败"这一点应该不成立吧,李每一次分配的内存才(36*64/8)B 这么小不应该吧,何况为mat 还成功了呢,(95*32/8)B它还大些呢 。
      

  6.   

    多谢大侠们的指点!我的问题解决了,原因是在产生异常的内存分配之前,调用了一个函数,该函数分配并初始化了一个结构体数组,但是在初始化该数组时发生了数组越界,可能因此影响了堆中内存的完整性,因此导致在后边继续分配内存时无法获取内存。非常感谢大侠们的建议,我会在以后的工作中尝试应用它们。不过我仍然对WINDOWS的内存、特别是堆的管理机制不甚清楚。大侠们有没有什么好的文档向小弟推荐一下呢?再次感谢!