Dll导出函数返回的堆空间指针不能delete是怎么回事
如题,今天写程序时候遇到了一个棘手的问题。
dll的导出函数 返回一个new过的堆指针。在main过程里不能delete。
dll代码:
- C/C++ code
#include "stdafx.h"BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ){ return TRUE;}void * G()//注意这里的导出函数是用def文件标注过的,可以getprocaddress{ return new char[50];}
调用DLL:
- C/C++ code
#include <windows.h>#include <stdio.h>typedef void *(*fG) ();int main(int argc, char* argv[]){ HMODULE hModule=LoadLibrary("Export.dll"); if(hModule==NULL) { printf("LoadLibrary error \n"); return 0; } fG G=(fG)GetProcAddress(hModule,"G"); if(G==NULL) { printf("GetProcAddress error \n"); return 0; } char * ret=(char*)G(); strcpy(ret,"Hello World"); printf("%s\n",ret); delete[] ret; FreeLibrary(hModule); return 0;}
代码可以正常编译,但调试时候弹出Debug Assertion Failed错误对话框。
具体内容是:
Program:F:\源代码\...
File: dbgdel.cpp
Line: 47
Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
For information on how your program can cause an assertion?
failure , see the Visual C++ documentation on asserts.
(press Retry to debug the application)
而且循环调用G导出函数会出现内存泄露,以至于卡死....
我都快愁死了,敢问大牛们 该怎么解决啊...
[解决办法]
主要是由于CRT库造成的,重载new/delete,不使用malloc/free分配内存,换成RtlAllocateHeap之类的
[解决办法]