简体   繁体   中英

String length() vs. char array strlen

I am capturing the payload of a network packet. The payload is in string form. Then I convert that string into char array . Now, I want to calculate the size of each packet payload

string payload;
payload = raw_payload->GetStringPayload();
char input[payload.length()];
strcpy(input,payload.c_str());
int size;
size=strlen(input);
LOGfile_length <<  size << " " << payload.length()  << endl;

When I print the size of the packet payloads, it comes different for string payload and char array payload. Why is this so?

140 1448
71 1448
67 1448
0 6
0 6
0 6
0 63

Now , I am doing this

memcpy ( input,  payload.c_str(), strlen(payload.c_str())+1 );

but still the sizes of the packets come different

Change the code to

char input[payload.length()+1];

This is because the the payload.length will return the number of characters in the string. We need one more byte to store the '\\0' character.

Hope this will help.

I suspect this is because Your payload contains \\0 characters.

You can easily check it with this code:

for(int i=0; i<payload.length(); i++) printf("%d\n", payload.c_str()[i]);

or, to make output shorter (thanks to Agent_L),

for(int i=0; i<payload.length(); i++) 
  if(payload.c_str()[i]==0) 
    printf("Found \\0 at %d\n", i);

and if You see 0 signs there -- You have bytearrays which can not be fit into plain-C strings.

PS and shintoZ is right too.

strcpy and strlen will stop as soon as they encounter a NUL (zero byte) in the input. NULs are very likely to appear in the middle of network packet data, which means you won't see any of the packet data after the first NUL.

A working approach would be to use string::length() and memcpy :

string payload = raw_payload->GetStringPayload();
char input[payload.length()];
size_t size = payload.length();
memcpy(input, payload.c_str(), size);
LOGfile_length << size << " " << payload.length() << endl;

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