字符串串联过程中添加的额外字符

Extra characters added during string concatenation

本文关键字:字符 添加 过程中 字符串      更新时间:2023-10-16

我正在编写一个C++代码,该代码将值连接到I2C消息系统的字符串中。我已经正确地处理了消息传递,但当我将字符串连接在一起时,代码错误地将不止我想要的三个值连接到字符串上。我写的代码如下:

void concatint(int value1, char address1, char address2)
{
    int alive1 = static_cast<int>(address1);
    int alive2 = static_cast<int>(address2);
    char* alive3 = (char*)malloc(sizeof(address1));
    char* alive4 = (char*)malloc(sizeof(address2));
    //alive3 = address1;
    //alive4 = address2;
    sprintf(alive3, "%2d", address1);
    sprintf(alive4, "%2d", address2);
    if (value1 < 10)
        readlength = 1;
    if (value1 >= 10 && value1 < 100)
        readlength = 2;
    if (value1 >= 100 && value1 < 1000)
        readlength = 3;
    if (value1 >= 1000 && value1 < 10000)
        readlength = 4;
    if (value1 >= 10000 && value1 < 100000)
        readlength = 5;
    if (value1 >= 100000 && value1 < 1000000)
        readlength = 6;
    if (value1 >= 1000000 && value1 < 10000000)
        readlength = 7;
    if (value1 >= 10000000 && value1 < 100000000)
        readlength = 8;
    *writedata = 0;
    itoa(value1, writedata, 10);
    strcpy(writeaddress, &address1);
    strcat(writeaddress, &address2);
    strcat(writeaddress, writedata);
    strcpy(readaddress, address1);
    strcat(readaddress, address2);
    typevalue = 1;
}

此功能的输入为:

concatint(5, ' ', ' ');

其中两个地址值是两个ASCii字符。

此代码的结果应该是:"5,ASCii字符连接在值之前。然而,当我运行代码时,得到的结果是:

" 05  055"

我的代码似乎在字符之间连接了一个额外的字符,我不确定上面的代码在哪里添加了这个字符。我已经逐步完成了代码,一切都应该正常,不确定我的问题在哪里。

前八行有未定义的行为:

void concatint(int value1, char address1, char address2)
{
    int alive1 = static_cast<int>(address1);
    int alive2 = static_cast<int>(address2);
    // Note that address1 is a char, not a char*, and as such sizeof(address1)
    // is guaranteed to be 1.  Thus we allocate one byte of storage.
    char * alive3 = (char*) malloc(sizeof(address1));
    char * alive4 = (char*) malloc(sizeof(address2));
    // Here we write two digits and a terminating NUL to that one byte
    // => undefined behaviour.  Cannot reason further about the program.
    sprintf(alive3, "%2d", address1);
    sprintf(alive4, "%2d", address2);

此外:

    strcpy(writeaddress, &address1);

也不行。address1是单个字符。&address1是指向该字符的指针,但后面没有尾随的NUL字符,因此它也不是传递给strcpy的有效指针。

使用std::string