std::strlen doesn't handle c strings that are not \0 terminated. Is there a safe version of it?
PS I know that in c++ std::string should be used instead of c strings, but in this case my string is stored in a shared memory.
EDIT
Ok, I need to add some explanation.
My application is getting a string from a shared memory (which is of some length), therefore it could be represented as an array of characters. If there is a bug in the library writing this string, then the string would not be zero terminated, and the strlen could fail.
strlen() in C-style strings can be replaced by C++ std::strings. sizeof() in C is as an argument to functions like malloc(), memcpy() or memset() can be replaced by C++ (use new, std::copy(), and std::fill() or constructors).
Ok, I need to add some explanation. My application is getting a string from a shared memory (which is of some length), therefore it could be represented as an array of characters. If there is a bug in the library writing this string, then the string would not be zero terminated, and the strlen could fail.
strlen() counts the number of characters up to, but not including, the first char with a value of 0 - the nul terminator.
The strlen() function calculates the length of a given string. The strlen() function is defined in string. h header file. It doesn't count null character '\0'.
You've added that the string is in shared memory. That's guaranteed readable, and of fixed size. You can therefore use size_t MaxPossibleSize = startOfSharedMemory + sizeOfSharedMemory - input; strnlen(input, MaxPossibleSize)
(mind the extra n
in strnlen
).
This will return MaxPossibleSize
if there's no \0
in the shared memory following input
, or the string length if there is. (The maximal possible string length is of course MaxPossibleSize-1
, in case the last byte of shared memory is the first \0
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With