11858

Simple Loops and String Length in C

Question:

I'm pretty new to C. Writing in Visual Studio 2015, I'm trying to safely prompt a user for a string by using fgets. I want to use fgets to get the string, check if the string is too long, and reprompt the user if it is until they enter a good string. Here is my code

/* * Nick Gilbert * COS317 Lab 2 Task 2 */ #include "stdafx.h" int main() { char str[10]; int isValid = 0; while (isValid == 0) { printf("Please enter a password: "); fgets(str, 10, stdin); if (strlen(str) == 9 && str[8] != '\n') { //http://stackoverflow.com/questions/21691843/how-to-correctly-input-a-string-in-c printf("Error! String is too long\n\n"); memset(&str[0], 0, sizeof(str)); } else { printf(str); isValid = 1; } } printf("Press 'Enter' to continue..."); getchar(); }

However, when I run this and enter a bad string, the excess characters get fed into the next fgets automatically!

<a href="https://i.stack.imgur.com/FVfRU.png" rel="nofollow"><img alt="enter image description here" class="b-lazy" data-src="https://i.stack.imgur.com/FVfRU.png" data-original="https://i.stack.imgur.com/FVfRU.png" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" /></a>

How can I fix this to do what I want it to do?

Answer1:

If the string read in by fgets doesn't end with a newline, call fgets in a loop until it does, then prompt the user again.

if (strlen(str) > 0 && str[strlen(str)-1] != '\n') { printf("Error! String is too long\n\n"); do { fgets(str, 10, stdin); } while (strlen(str) > 0 && str[strlen(str)-1] != '\n') { }

Also, never pass a variable at the first argument to printf, particularly if the contents of that variable comes from user entered data. Doing so can lead to a <a href="https://stackoverflow.com/questions/7459630/how-can-a-format-string-vulnerability-be-exploited" rel="nofollow">format string vulnerability</a>.

Answer2:

Try this:

#include "stdafx.h" int main() { char str[10]; int isValid = 0; while (isValid == 0) { printf("Please enter a password: "); fgets(str, str, stdin); if (strlen(str) == 9 && str[8] != '\n') { //http://stackoverflow.com/questions/21691843/how-to-correctly-input-a-string-in-c printf("Error! String is too long\n\n"); memset(str, 0, sizeof(str)); } else { printf("%s",str); isValid = 1; } } printf("Press 'Enter' to continue..."); getchar(); }

In addition:

While using memset() you can directly use the array_name rather &array_name[0].

Recommend

  • How to make Regex ignore a pattern following a specific group
  • Precompiled header and Visual Studio
  • ERROR LNK2019:unresolved external symbol, c++ [duplicate]
  • Failed to start an instrument test from Firebase gcloud command line
  • Is this an expected behavior with return keyword on JavaScript
  • How to bind Backbone model to jqGrid?
  • How do I fix “The program issued a command but the command length is incorrect.” error when calling
  • Combining two different ActiveRecord collections into one
  • bad substitution shell- trying to use variable as name of array
  • wxPython: displaying multiple widgets in same frame
  • Stop Bash Script if Hive Fails
  • C: Incompatible pointer type initializing
  • custom UITableViewCell with image for highlighting
  • Google Custom Search with transparent background
  • Why value captured by reference in lambda is broken? [duplicate]
  • AES padding and writing the ciphertext to a disk file
  • Obtain ObjectIdHex value from mgo query
  • Volusion's generic SQL folder, functionality
  • How to set/get protobuf's extension field in Go?
  • output of program is not same as passed argument
  • JSON with duplicate key names losing information when parsed
  • Can I have the cursor start on a particular column by default in jqgrid's edit mode?
  • Convert array of 8 bytes to signed long in C++
  • Why is the timeout on a windows udp receive socket always 500ms longer than set by SO_RCVTIMEO?
  • Rearranging Cells in UITableView Bug & Saving Changes
  • Akka Routing: Reply's send to router ends up as dead letters
  • 0x202A in filename: Why?
  • Circular dependency while pushing http interceptor
  • Linker errors when using intrinsic function via function pointer
  • Hits per day in Google Big Query
  • How get height of the a view with gone visibility and height defined as wrap_content in xml?
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • How does Linux kernel interrupt the application?
  • How to get Windows thread pool to call class member function?
  • LevelDB C iterator
  • unknown Exception android
  • Checking variable from a different class in C#
  • Sorting a 2D array using the second column C++
  • Python/Django TangoWithDjango Models and Databases
  • java string with new operator and a literal