-2

我正在尝试将 a 转换const unsigned char*char*并制作副本。我尝试了以下代码的几种变体,但通常会出现内存异常。此函数驻留在用 C 编写的应用程序中。

下面的函数是我想要创建的

//global variable
char* copiedValue;

void convertUnsignedChar(const unsigned char* message){

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

}
4

2 回答 2

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);
于 2018-08-01T02:38:40.340 回答
1

您的问题的很大一部分是sizeof(message)它为您提供了指针的大小,而不是它指向的内容。

将长度传递给函数,或者(如果数据是以空字符结尾的字符串)用于strlen获取长度(但不要忘记为终止符添加一个!)或上述strdup函数(如果可用)。

于 2018-08-01T02:33:55.343 回答