Return unsigned char as a hex value

-1

I'm aiming to be able to return unsigned char as a hex values, this is so I can pass the value from my client to server side.

How my data is generated before trying to be converted into hex:

unsigned char *TestClass::GetKey()
{
    // Generate a key of length 32 bytes
    memset(this->szKey, 0, 32);
    RAND_bytes(this->szKey, 32);

    return this->szKey;
}

This what i've currently got so far:

TestClass myTestClass;

void CJSCallDoc::OnDocumentComplete(LPCTSTR strURL,LPDISPATCH pDisp)
{
    unsigned char szKey = hex_print(myTestClass.GetKey());
}

unsigned char CJSCallDoc::hex_print(unsigned char* pv)
{
    unsigned char *p = pv;
    if (NULL == pv)
    {
        return NULL;
    }
    else
    {
        char storedString[256];

        size_t len = strlen((const char*)pv);
        size_t i = 0;

        for (; i < len; ++i)
        {
            strcpy_s(storedString, 256, "Test");
            strcat_s(storedString, reinterpret_cast<char*>(*p++));
        }

        return *storedString;
    }
}

The problem I'm having is with this line:

strcat_s(storedString, reinterpret_cast<char*>(*p++));

This line causes my application to crash and this is the following error I get:

Unhandled exception at 0x01664467 in TestApp.exe: 0xC0000005: Access violation reading location 0x000000FE.

and the error takes me to tcscat_s.inl:

---> while ((*p++ = *_SRC++) != 0 && --available > 0)
{
}

However when I try and do the following it works fine:

unsigned char CJSCallDoc::hex_print(unsigned char* pv)
{
    unsigned char *p = pv;
    if (NULL == pv)
    {
        return NULL;
    }
    else
    {
        char storedString[256];

        size_t len = strlen((const char*)pv);
        size_t i = 0;

        for (; i < len; ++i)
        {
            strcpy_s(storedString, 256, "Test");
            strcat_s(storedString, "WORKS");
        }

        return *storedString;
    }
}

Could someone explain to me, what I'm doing wrong and give me some advice in the right direction?

c++
asked on Stack Overflow Nov 26, 2015 by YaBCK • edited Nov 26, 2015 by YaBCK

1 Answer

3

The problem is that you are casting your data to address, in:

strcat_s(storedString, reinterpret_cast<char*>(*p++));

*p++ is equal to whatever your string contains - first element is p from your example, so you are casting this p - decimal value 112, to char*. strcat_s will try to read string from this location which immediately ends with segfault.

answered on Stack Overflow Nov 26, 2015 by marcinj

User contributions licensed under CC BY-SA 3.0