reinterpret_cast on pointers pitfall between char and unsigned char?
-
17-04-2021 - |
Question
I'm using the following function in order to create an UUID and write it in a human-readable form into a pre-allocated buffer. Something goes wrong.
void createUUID(char* pDst)
{
UUID lUUIDObj;
UuidCreate(&lUUIDObj);
unsigned char* lDest = reinterpret_cast<unsigned char*>(pDst);
UuidToStringA(&lUUIDObj, &lDest)
}
At the end of the method, the debugger says:
- lDest = 0x01fe4fd8 "df4a5ed8-c0d2-495a-84d7-ce0e07cf2113"
- pDst = 0x0012ec7c "ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ"
I thought that both would have the same content, however it is not the case.
What happened? Thanks.
Solution
Looking at the documentation for UuidToStringA
, it says:
The RPC run-time library allocates memory for the string returned in the StringUuid parameter.
This means that after the call lDest
does no longer point to pDst
.
OTHER TIPS
void createUUID(char* pDst)
{
UUID lUUIDObj;
UuidCreate(&lUUIDObj);
unsigned char* lDest = reinterpret_cast<unsigned char*>(pDst);
//UuidToStringA(&lUUIDObj, &lDest);
UuidToStringA(&lUUIDObj, lDest);
}
Looks like you clobbered the value of lDest
without changing the values it originally pointed to.
In order to complete Joachim Pileborg's answer, here is the corrected function:
void createUUID(char* pDst)
{
UUID lUUIDObj;
UuidCreate(&lUUIDObj);
unsigned char* lTmpStr;
UuidToStringA(&lUUIDObj, &lTmpStr);
sprintf(pDst, reinterpret_cast<char*>(lTmpStr));
RpcStringFreeA(&lTmpStr);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow