求教一个free的问题
我在函数unsigned int Continumax(char** pOutputstr, char* intputstr)中,有这样一段代码:
*pOutputstr = (char*)malloc(2);
if(NULL == *pOutputstr)
{
return 0;
}
memset(*pOutputstr, 0, 2);
strncpy(*pOutputstr, "", 1);
这样写的话在这样使用时不会出问题:
char *pOutputstr = NULL;
unsigned int nLength = Continumax(&pOutputstr, intputstr);
CPPUNIT_ASSERT(nLength == 1);
CPPUNIT_ASSERT((pOutputstr != NULL) && (strcmp(pOutputstr,"1") == 0));
free(pOutputstr);
但是这样写的话在像上面那样使用free就会导致异常,是什么原因呢:
*pOutputstr = (char*)malloc(2);
if(NULL == *pOutputstr)
{
return 0;
}
memset(*pOutputstr, 0, 2);
*pOutputstr="";
[解决办法]
楼上的,在看看楼主的代码先吧
*pOutputstr="";
//这个是干啥? 这里的意思是把""这个字符串常量的地址赋值给*pOutputstr的,
//你之前自己malloc的地址指针已经丢失了(也就是内存泄漏),
//你后面free的不是malloc的地址,是静态地址,你free肯定出错阿!