Hello! Here, in fact, is a question about C ++: a simple reading of a string using the gets () function causes a warning: it’s not safe. Why is that? And the second question after - why does the program work correctly, because I did not include the header, which is needed by the gets () function? Thanks to all! A warning Gets function

  • 2
    It is written about this even in the wiki , not to mention more specialized resources ... Was laziness born ahead of you? - PinkTux
  • There is an error in the program, in the word "read". - Vladimir Gamalyan

2 answers 2

The problem is that gets() reads everything up to the '\n' character or the end of the file, regardless of size. You allocated 100 bytes, entered 200 - where will the extra 100 bytes be written to? on top of something on the stack. Than any insidious hackers use it, substituting the input such that it overwrites what is necessary where it is necessary and does what the hacker needs as a result ...

Well, it means that your <iostream> indirectly includes the desired title ...

    The gets function does not control the size of the input data in a character array, and therefore it can write data outside the character array.

    The gets function is no longer supported by the C standard. Instead, use the fgets function. For example, for your program, the call function might look like this:

     fgrts( str, sizeof( str ), stdin ); 

    This function also enters a newline character in a character array if there is room for it in the array. In most cases, it should be removed from the character array, since it is not needed. In C ++, this can be done in the following ways.

     #include <cstring> //... fgrts( str, sizeof( str ), stdin ); str[ std::strcspn( str, "\n" ) ] = '\0'; 

    Or

     if ( ( char *p = std::strchr( str, '\n' ) ) *p = '\0'; 

    In C ++, it is better to use standard C ++ functions to enter data into a character array, such as a member function of the getline class. For example,

     std::sin.getline( str, sizeof( str ) ); 

    In general, if you are working with standard C input / output functions, you should explicitly include the <cstdio> header. Regarding your program, apparently, the <iostream> header file itself included this C header in your program.