简体   繁体   中英

string size after converting const unsigned char[] to std::string

I tried to convert unsigned char array to an std::string of size 16. But I don`t know why result string size is different. I want to know the reason.

#include <iostream>

using namespace std;

const unsigned char t[16] = { 0x1E, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 ,0x08 ,0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15 };
const unsigned char t2[16] = { 0x1E, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 ,0x08 ,0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15 };
const unsigned char t3[16] = { 0x44, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47 ,0x68 ,0x69, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65 };

int main() {
    string a, a2, a3;
    a = static_cast<std::string>(reinterpret_cast<const char*>(t));

    a2.assign(reinterpret_cast<const char*>(t2), 16);

    a3.assign(reinterpret_cast<const char*>(t3));   

    cout << "size : " << a.size() << endl;
    for (int i = 0; i < a.size(); i++)
        printf("0x%02X ", a.c_str()[i]);
    cout << endl << endl;

    cout << "size2 : " << a2.size() << endl;
    for (int i = 0; i < a2.size(); i++)
        printf("0x%02X ", a2.c_str()[i]);
    cout << endl << endl;

    cout << "size3 : " << a3.size() << endl;
    for (int i = 0; i < a3.size(); i++)
        printf("0x%02X ", a3.c_str()[i]);
    cout << endl << endl;

    return 0;
}

result

size: 56

0x1E 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x10 0x11 0x12 0x13 0x14 0x15 0x1E 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x10 0x11 0x12 0x13 0x14 0x15 0x44 0x41 0x42 0x43 0x44 0x45 0x46 0x47 0x68 0x69 0x60 0x61 0x62 0x63 0x64 0x65 0x5F 0x41 0x72 0x67 0x4C 0x69 0x73 0x74

size2: 16

0x1E 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x10 0x11 0x12 0x13 0x14 0x15

size3: 24

0x44 0x41 0x42 0x43 0x44 0x45 0x46 0x47 0x68 0x69 0x60 0x61 0x62 0x63 0x64 0x65 0x5F 0x41 0x72 0x67 0x4C 0x69 0x73 0x74

case 1: input is not explicitly null-terminated, and likely those global arrays are placed in memory sequentially, so you get at least 48 bytes without zeros, finally it finds some zero 8 bytes ahead, so total is 56.

case 2: here you give it explicit length, and that's the correct way to do things in case of null terminator absence.

case 3: similar to case 1, but just starts from array 3, and takes same extra 8 bytes until null terminator found somewhere.

Solutions: either add null terminators (zero byte) or use variant with explicit length specification.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM