F
F
FX-Mercury2015-03-23 13:20:13
Programming
FX-Mercury, 2015-03-23 13:20:13

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

3 answer(s)
A
Armenian Radio, 2015-03-23
@gbg

In C++, descending to raw pointers is extremely rare.

V
Vladimir Martyanov, 2015-03-23
@vilgeforce

Standard problem: inside a function, str can go into memory to which it will not have access. And an exception will be thrown.

S
Stanislav Makarov, 2015-03-23
@Nipheris

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 question

Ask a Question

731 491 924 answers to any question