0

Is it safe to use strlen () in C++?

Coding a little program and using a security tool (flawfinder) I have realized that strlen() doesn't handle strings that are not \0 terminated, because of this, an undefined behavior may occurr. So, I guess is not safe to use strlen ()? which another function can I use in C++ to get the length of the string? I solved the problem using sizeof (), it could be an alternative? or is there another better function to replace strlen ()? Note: in the code I used an array of string characters instead std::string. char str [] = "example";

9th Dec 2018, 2:17 AM
Eduardo Perez Regin
Eduardo Perez Regin - avatar
5 Respuestas
+ 1
C-style string are, by definition, "null-terminated character array" then, except when use custom string representation, strlen is safe. Futhermore, C11 standard define strlen_s function which take another parameter that indicate bound index which check for null-character existence.... See here https://en.cppreference.com/w/c/string/byte/strlen
9th Dec 2018, 12:55 PM
KrOW
KrOW - avatar
+ 3
Sorry but, in your example, what happen if you call: strlen(str); ???
9th Dec 2018, 8:46 AM
KrOW
KrOW - avatar
+ 3
👍👍👍
10th Dec 2018, 8:11 AM
KrOW
KrOW - avatar
+ 1
KrOW it works fine, strlen () gives me the length of the string, but my point here is that if there is another alternative besides strlen(), because if strlen () finds a string without the '\0', it may occurr and undefined behavior, the risk will be there
9th Dec 2018, 12:16 PM
Eduardo Perez Regin
Eduardo Perez Regin - avatar
+ 1
I see, thx!
10th Dec 2018, 4:29 AM
Eduardo Perez Regin
Eduardo Perez Regin - avatar