Why does this switch statement end the while loop when it's run?

Viewed 108

I want this program to break from the switch and back into the while loop. Why isn't it working?

I put a switch statement within a while loop. I think the breaks are interfering with the while loop making it break early. How could I fix this problem?

#include <stdbool.h>
#include <stdio.h>


 int main(void)
 {
 
 bool ON_status = true;
 char option = '0';

  while (ON_status == true)
  {
      printf("enter option 1, 2, 3, or 4.\n");
      printf("Select an option from the menu above then press the enter key:  ");
      scanf("%1s", &option);

      switch (option)
      {
      case '1':
           printf("option1 was selcted");
           break;

      case '2':
           printf("option2 was selcted");
           break;

      case '3':
           printf("option3 was selcted");
           break;

      case '4':
           printf("option4 was selcted");
           ON_status = false;
           break;

      default:
           break;
      }
  }
 return 0;
}
1 Answers

The issue with your code is that the line

scanf("%1s", &option);

overflows the memory in option.

Strings in C are null-terminated. So '%1s' stores one character and a null terminator. But your option variable is only one character long, so where does the zero (or NULL, NUL, null depending on your naming) go?

In this case, because ON_status and option are declared close by in memory it is overwriting ON_status.

To see that this what is going on you could print the value of ON_status outside the switch and you would observe that it was 0.

To fix the problem, I think I would replace your scanf with

option = getc(stdin);
Related