试图清理一些代码,我想知道以下是否是将 uint16_t 转换为 wchar_t 的安全方法。
#if ! defined(MARKUP_SIZEOFWCHAR)
#if __SIZEOF_WCHAR_T__ == 4 || __WCHAR_MAX__ > 0x10000
#define MARKUP_SIZEOFWCHAR 4
#else
#define MARKUP_SIZEOFWCHAR 2
#endif
void FileReader::parseBuffer(char * buffer, int length)
{
//start by looking for a vrsn
//Header seek around for a vrns followed by 32 bit size descriptor
//read 32 bits at a time
int cursor = 0;
char vrsn[5] = "vrsn";
cursor = this->searchForMarker(cursor, length, vrsn, buffer);
int32_t size = this->getObjectSizeForMarker(cursor, length, buffer);
cursor = cursor + 7; //advance cursor past marker and size
wchar_t *version = this->getObjectForSizeAndCursor(size, cursor, buffer);
wcout << version;
delete[] version; //this pointer is dest from getObjectForSizeAndCursor
}
-
wchar_t* FileReader::getObjectForSizeAndCursor(int32_t size, int cursor, char *buffer) {
int wlen = size/2;
uint32_t *dest = new uint32_t[wlen+1];
unsigned char *ptr = (unsigned char *)(buffer + cursor);
for(int i=0; i<wlen; i++) {
#if MARKUP_SIZEOFWCHAR == 4 // sizeof(wchar_t) == 4
char padding[2] = {'\0','\0'};
dest[i] = (padding[0] << 24) + (padding[1] << 16) + (ptr[0] << 8) + ptr[1];
#else // sizeof(wchar_t) == 2
dest[i] = (ptr[0] << 8) + ptr[1];
#endif
ptr += 2;
cout << ptr;
}
return (wchar_t *)dest;
}
我使用填充的方式有任何范围问题吗?当我delete dest[]
在调用函数中时,我会泄漏填充吗?