求指点:malloc在函数中申请内存,外部free总失败
求指导:malloc在函数中申请内存,外部free总失败
代码:
void freeDataBuf(unsigned short *pusGetData)
{
if (NULL != pusGetData)
{
free(pusGetData);
pusGetData = NULL;
}
return;
}
int main()
{
......
while (1)
{
......
iRtnGetData = GetDataFromServer(&resultData,......,&enDataNum);
......
/* 调用的dll中函数GetDataFromServer()获取了服务器数据,函数中malloc的缓存没有释放,此处释放 */
freeDataBuf(resultData);
}
return 0;
}
单步跟踪代码到freeDataBuf(resultData);立刻出现错误:
Debug Err!
Program: ...$Path$Client.exe
HEAP CORRUPTION DETECTED:after Normal block(#495971) at 009C7FD8.
CRT detected that the application wrote to memory after end of heap buffer.
(Press Retry to debug the application)
提示说明heap空间不够?但其中GetDataFromServer()中malloc申请的空间大小是300字节。请教高人们,这是在哪里出错了?
------解决方案--------------------
你试试传二级指针,看能不能释放掉
------解决方案--------------------
函数本身需要使用指针的指针,这样外面才能得到分配的内存
------解决方案--------------------
freeDataBuf(resultData);
freeDataBuf();函数的参数是指针,但是传进去的不是指针,所以错误;
下面是测试正常的函数:
代码:
void freeDataBuf(unsigned short *pusGetData)
{
if (NULL != pusGetData)
{
free(pusGetData);
pusGetData = NULL;
}
return;
}
int main()
{
......
while (1)
{
......
iRtnGetData = GetDataFromServer(&resultData,......,&enDataNum);
......
/* 调用的dll中函数GetDataFromServer()获取了服务器数据,函数中malloc的缓存没有释放,此处释放 */
freeDataBuf(resultData);
}
return 0;
}
单步跟踪代码到freeDataBuf(resultData);立刻出现错误:
Debug Err!
Program: ...$Path$Client.exe
HEAP CORRUPTION DETECTED:after Normal block(#495971) at 009C7FD8.
CRT detected that the application wrote to memory after end of heap buffer.
(Press Retry to debug the application)
提示说明heap空间不够?但其中GetDataFromServer()中malloc申请的空间大小是300字节。请教高人们,这是在哪里出错了?
------解决方案--------------------
你试试传二级指针,看能不能释放掉
------解决方案--------------------
函数本身需要使用指针的指针,这样外面才能得到分配的内存
------解决方案--------------------
freeDataBuf(resultData);
freeDataBuf();函数的参数是指针,但是传进去的不是指针,所以错误;
下面是测试正常的函数:
- C/C++ code
#include<stdio.h> #include<stdlib.h> #include<string.h> free_(char *str) { if(NULL != str) { free(str); str = NULL; } return; } main() { /* char a[][10] = {"China","Beijing"}; char *p; p = (char *)a; printf("%s\n",p+10); */ char *b = (char *)malloc(sizeof(char) * 30); strcpy(b,"! LOVE CHINA!"); printf("%s size is %d\n",b,strlen(b)); free_(b); return 0; }
------解决方案--------------------
你首先得肯定从GetDataFromServer得到的iRtnGetData是用malloc分配所得到的,如果是的话,就应该不会错。
------解决方案--------------------
你的resultData是指针,然后你用GetDataFromServer函数把resultData的地址传入了,那么用malloc申请的空间应该是赋给resultData的地址,而不是resultData本身吧。然后你的freeDataBuf释放的是一个指针,但是你的resultData并没有申请过空间,所以应该会报错。
如果说的不对,请指出。
------解决方案--------------------
据我多年的经验,很可能是溢出了,你多写了些东西进去,debug版本,会用cd填充那些位置,你自己调试一下吧,注意cd部分的内存。
我去年弄xp,借用点内存,就是用的fe部分,当然用完了要填回去,除非你hook掉系统的处理。
------解决方案--------------------
其实断言已经说的很详细,只是你不去看,呵呵呵