Search code examples
cvisual-studiounsigned-char

How to copy ULONG into PUCHAR


Today I am trying to copy a unsigned long variable into the contents of an unsigned char * variable.

The reasoning for this is, I wrote an RC4 cipher which requires the key input to be a unsigned char *, I am using the SYSTEMTIME class to obtain a value & combining it with a randomly generated long value to obtain my key for RC4 - I am using it as a timestamp for a user created account to mark in my sqlite dbs.

Anyways, the problem I ran into is that I cannot copy the ULONG into PUCHAR.

I've tried

wsprintfA(reinterpret_cast<LPSTR>(ucVar), "%lu", ulVar);

and I've tried

wsprintfA((LPSTR)ucVar, "%lu", ulVar);

However, after executing my program the result in ucVar is just empty, or it doesn't even compute, and crashing the application.

[edit 1]

I thought maybe the memcpy approach would work, so I tried declaring another variable and moving it into ucVar, but it still crashed the application - i.e. It didn't reach the MessageBox():

unsigned char *ucVar;
char tmp[64]; // since ulVar will never be bigger than 63 character + 1 for '\0'

wsprintfA(tmp, "%lu", ulVar);
memcpy(ucVar, tmp, sizeof(tmp));
MessageBox(0, (LPSTR)ucVar, "ucVar", 0);

[/edit 1]

[edit 2]

HeapAlloc() on ucVar with of size 64 fixed my problem, thank you ehnz for your suggestion!

[/edit 2]

Can anyone give me some approach to this problem? It is greatly appreciated!

Regards, Andrew


Solution

  • Unless you have ownership of memory you're trying to use, all kinds of things can happen. These may range from the error going unnoticed because nothing else already owns that memory, to an instant crash, to a value that disappears because something else overwrites the memory between the time that you set it and the time that you attempt to retrieve a value from it.

    Fairly fundamental concepts when dealing with dynamic memory allocation, but quite the trap for the uninitiated.