strlen() gives wrong size cause of null bytes in array

情到浓时终转凉″ 提交于 2021-02-08 12:11:46

问题


I have a dynamic char array that was deserialized from a stream.

Content of char *myarray on the file (with a hexal editor) :

      4F 4B 20 31 32 20 0D 0A 00 00 B4 7F

strlen(myarray) returns 8, (must be 12)


回答1:


strlen(myarray) returns the index of the first 00 in myarray.




回答2:


strlen counts the characters up to the first 0 character, that's what it's for.

If you want to know the length of the deserialized array, you must get that from somewhere else, the deserialization code should know how large an array it deserialized.




回答3:


Which language are you asking about?

In C, you'll need to remember the size and pass it to anything that needs to know it. There's no (portable) way to determine the size of an allocated array given just a pointer to it and, as you say, strlen and other functions that work with zero-terminated strings won't work with unterminated lumps of data.

In C++, use std::string or std::vector<char> to manage a dynamic array of bytes. Both of these make the size available, as well as handling deallocation for you.




回答4:


9th char is 00. i.e '\0'. This is the reason you are getting 8 instead of 12.
strlen() takes it as Null terminator.




回答5:


A C-style String is terminated by NULL, and your char* contains a NULL-Byte at the 9th position, thus strlen returns 8, as it counts the elements until it finds a NULL byte.

(from http://www.cplusplus.com/reference/clibrary/cstring/strlen/):

A C string is as long as the amount of characters between the beginning of the string and the terminating null character.

As you're using the char* for binary data, you must not use the strlen function, but remember (pass along) the size of the char array.

In your case, you could serialize the size of the dynamic array on transmission, and deserialize it before allocating / reading the array.




回答6:


From cplusplus.com (http://www.cplusplus.com/reference/clibrary/cstring/strlen/):

The length of a C string is determined by the terminating null-character

You can not expect that it would count the whole string if you have '\0' in the middle of it.

It such scenarios I have found it to be best to serialize the length of the message alongside the data in the stream. For example, you first serialize the length of the char array - 12 and then you serialize the actual data (characters). That way when you read the data you would first read the length and then you can read that much characters and be sure that is your char array.



来源:https://stackoverflow.com/questions/11827531/strlen-gives-wrong-size-cause-of-null-bytes-in-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!