How to convert const unsigned char* payLoad to char* and copy it?

767 Views Asked by At

I'm trying to convert a const unsigned char* to char* as well as make a copy. I have tried several variations of the code below but I usually get a memory exception. This function resides in an application written in C.

The below function is what I'm trying to create

//global variable
char* copiedValue;

void convertUnsignedChar(const unsigned char* message){

    copiedValue = malloc(sizeof(message));
    (void)memcpy(copiedValue, message, sizeof(message));

}
2

There are 2 best solutions below

0
On

A large part of your problem is sizeof(message) which gives you the size of the pointer, not what it points to.

Either pass the length to the function, or (if the data is a null-terminated string) use strlen to get the length (but don't forget to add one for the terminator!) or the above mentioned strdup function (if available).

1
On

malloc(sizeof(message)) only allocates space for a char * pointer, probably 8 bytes. You need to allocate space for the data which message points to.

There's a bit of a problem: how much data is pointed at by message? Is it null terminated? Let's assume it is, then you can use strlen. Don't forget space for the null byte!

copiedValue = malloc(strlen((char*)message) + 1);

Similarly for memcpy.

memcpy(copiedValue, message, strlen((char*)message) + 1);

Note, there's no need to cast memcpy's return value to void.


Or use the POSIX strdup function.

copiedValue = strdup((char *)message);