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";
5 Respostas
+ 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
+ 3
Sorry but, in your example,
what happen if you call:
strlen(str);
???
+ 3
👍👍👍
+ 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
+ 1
I see, thx!