快过年了,成都的天气不错,心情也很舒畅。
我们接着来讲,_strdup是经常用来复制字符串的函数。
1.介绍
函数签名:char *_strdup(const char *strSrc)
返回值:返回值向北复制的字符串的指针,所需空间由malloc分配并且必须手动free释放
2.实现
inline tChar *tStrDup(const tChar *pString)
{
tChar *pMemory = NULL;
size_t size = 0;
if( !pString )
return(NULL);
size = tStrLen(pString) + 1;
if( pMemory = static_cast(malloc(size)) )
{
tStrCopyS(pMemory, size, pString);
return pMemory;
}
return NULL;
}
其中,tStrLen位strlen的实现,tStrCopyS是strcpy_s的实现,而strcpy_s是MS提供的函数,借助了标准函数strncpy。这些函数的实现在后面的文章中会单独介绍,这里只是用到了,略过~
3.测试
tChar seps[] = _T(" ,/t/n");
tChar *p = CY_CRT::tStrDup(seps);
wcout << p << endl;
free(p);
4.后记
这个函数的设计我认为并不太好,原因也很简单:可能忘记释放内存。解决方案可以是客户端申请内存,再以参数的方式传入函数。其实,用户来考虑字符串中内存的分配释放就不是好的设计,这也间接证引出std::string,自动管理内存的生存。