MultiByteToWideChar()函数

来源:百度知道 编辑:UC知道 时间:2024/09/24 05:04:54
iLength = MultiByteToWideChar( CP_ACP, 0, pStringIn, -1, NULL, 0 ) ; // pStringIn = "river" iLength = 6
pWideStr = malloc( iLength ) ; //分配6字节内存
MultiByteToWideChar( CP_ACP, 0, pStringIn, -1, pWideStr, iLength ) ; //pWideStr = WCHAR(river)

这段程序运行良好.可是有点困扰着我,pWideStr指向的内存块是6字节,而宽字符的"river"需要12个字节才能装下.程序这样不会溢出吗?

pWideStr = malloc( iLength ) ; //分配6字节内存

会导致溢出,而且 C++ 建议使用 new 和 delete 代替 malloc 和 free:

pWideStr = new WCHAR[iLength + 1] ; //分配(6+1)*2=14字节内存
MultiByteToWideChar( CP_ACP, 0, pStringIn, -1, pWideStr, iLength );
pWideStr[iLength] = 0; // 追加 \0
...
delete[] pWideStr;

你malloc完了以后可以直接free啊,new delete 底层还是调用的malloc free 在c++中照样使用,没有任何问题