-
May 17th, 2023, 02:42 PM
#1
fgets and overrun buffer
I want to input string by fgets(buffer, 5, stdin) e.g. "stop", "lame", "rear"
char buffer[5];
If I type string which has a length of 20 characters, the next calls to fgets() keep partial content of previous input, what can I avoid it into Ansi C please?
-
May 17th, 2023, 02:57 PM
#2
Re: fgets and overrun buffer
Your three basic steps are
- input
- validation
- conversion.
That you only want 4 characters falls into the latter stages.
So normally, I would do
Code:
char buff[BUFSIZ];
if ( fgets(buff, BUFSIZ, stdin) ) { // input
if ( strlen(buff) > 4 ) { // validation
strmcpy(buffer, buff, 4); // conversion
buffer[4] = '\0';
}
}
So if they did type 20 chars, the initial call to fgets would have consumed the excess for you from the outset.
Only people trying to DoS your program would ever get near trying to fill BUFSIZ characters without pressing return.
-
May 17th, 2023, 10:58 PM
#3
Re: fgets and overrun buffer
 Originally Posted by salem_c
Your three basic steps are
Only people trying to DoS your program would ever get near trying to fill BUFSIZ characters without pressing return.
I'm trying to limit input only for X number of characters, so that, while user is typing, He can show only at maximum X characters.
The excessive input should be hidden
-
May 18th, 2023, 12:19 AM
#4
Re: fgets and overrun buffer
Well there's no way in ANSI C to just input 4 characters and NOT display anything else on the line until return is pressed.
-
May 18th, 2023, 03:58 AM
#5
Re: fgets and overrun buffer
If supported, the closest you're going to get is to use getch() (or _getch() if using MS VS) from conio.h - but this isn't 'standard' c. This function will accept 1 char without echo. So you'd need a loop etc to obtain 4 chars
https://learn.microsoft.com/en-us/cp...?view=msvc-170
All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!
C++23 Compiler: Microsoft VS2022 (17.6.5)
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|