Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a safe version of strlen?

Tags:

c++

c

string

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.

like image 207
BЈовић Avatar asked May 09 '11 10:05

BЈовић


People also ask

What can I use instead of strlen?

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).

Can strlen fail?

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.

Does strlen need null terminator?

strlen() counts the number of characters up to, but not including, the first char with a value of 0 - the nul terminator.

Does strlen () include null?

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'.


1 Answers

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)

like image 162
MSalters Avatar answered Sep 18 '22 14:09

MSalters