在 VC++6.0 中使用 malloc和 free,
下面两个函数中感觉没什么区别呀,但第一段在内存释放的时候就有内存访问异常的问题而第二段就没有,什么问题呀 ?
typedef struct _SEARCH_PATH
{
unsigned char ucPathNum;
unsigned char ucMaxPath;
unsigned char * pucRejectMsgFlag;
}SEARCH_PATH;
SEARCH_PATH *gpstrSearchPath; uint16 *gpustmp;int funtion1(void)
{ gpstrSearchPath = (SEARCH_PATH * )malloc(sizeof(SEARCH_PATH)* 5);
if (NULL != gpstrSearchPath )
{
for (i=0;i<5;i++)
{
gpstrSearchPath[i].pucRejectMsgFlag = (unsigned char * )malloc(sizeof(unsigned char)* 10);
if (NULL == gpstrSearchPath[i].pucRejectMsgFlag ) return 1;
}
}
else
{
return 1;
}
.....................
if (NULL != gpstrSearchPath )
{
for (i=0;i<5;i++)
{
free(gpstrSearchPath[i].pucRejectMsgFlag); //这里释放内存 出错 }
} free(gpstrSearchPath);
return 0;
}int funtion2(void)
{ gpustmp = (uint16 * )malloc(sizeof(uint16)* 5);
if (NULL != gpustmp )
{
}
else
{
return 1;
}
.....................
free(gpustmp); //这样就没问题
return 0;
}
下面两个函数中感觉没什么区别呀,但第一段在内存释放的时候就有内存访问异常的问题而第二段就没有,什么问题呀 ?
typedef struct _SEARCH_PATH
{
unsigned char ucPathNum;
unsigned char ucMaxPath;
unsigned char * pucRejectMsgFlag;
}SEARCH_PATH;
SEARCH_PATH *gpstrSearchPath; uint16 *gpustmp;int funtion1(void)
{ gpstrSearchPath = (SEARCH_PATH * )malloc(sizeof(SEARCH_PATH)* 5);
if (NULL != gpstrSearchPath )
{
for (i=0;i<5;i++)
{
gpstrSearchPath[i].pucRejectMsgFlag = (unsigned char * )malloc(sizeof(unsigned char)* 10);
if (NULL == gpstrSearchPath[i].pucRejectMsgFlag ) return 1;
}
}
else
{
return 1;
}
.....................
if (NULL != gpstrSearchPath )
{
for (i=0;i<5;i++)
{
free(gpstrSearchPath[i].pucRejectMsgFlag); //这里释放内存 出错 }
} free(gpstrSearchPath);
return 0;
}int funtion2(void)
{ gpustmp = (uint16 * )malloc(sizeof(uint16)* 5);
if (NULL != gpustmp )
{
}
else
{
return 1;
}
.....................
free(gpustmp); //这样就没问题
return 0;
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货