-2

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));

}
Jim
  • 373
  • 5
  • 18
  • *Why* do you need to "convert" the data? Do you need to modify it? While not in standard C (but in other standards) you probably have a `strdup` function which possibly might do what you want (if the contents is a string). Oh and don't forget to `free` the data sometime, or you'll have a memory leak. – Some programmer dude Aug 01 '18 at 02:30
  • Why do you need to convert the pointer? If you have to remove the `const` qualifier, your system design is most probably broken, as it is not `const`-correct. – too honest for this site Aug 01 '18 at 04:20

2 Answers2

1

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).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

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);
Schwern
  • 153,029
  • 25
  • 195
  • 336