Answer the question
In order to leave comments, you need to log in
I don't know signs very well. What pitfalls does my function hide?
size_t str_len( const char *str )
{
const char *begin = str;
while( *str++ != '\0' )
;
return ( str - begin - 1 );
}
void main( void )
{
char *text = "hello";
cout<<str_len(text);
cin.get();
system("pause");
}
Answer the question
In order to leave comments, you need to log in
Standard problem: inside a function, str can go into memory to which it will not have access. And an exception will be thrown.
And when people got tired of the fact that such functions go into memory to which the function does not have access (including due to specially fabricated parameters that lead to unpleasant consequences, see buffer overflow), they came up with paired "safe" options, for example strnlen . There, in addition to the string, the second parameter indicates the maximum possible length of the transmitted string (for example, for a file path it will be 255 characters). This is usually the length of some buffer into which the string is placed. There are similar pairs for other functions: strcpy/strncpy, etc.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question