如何修复C语言中的Run-Time Check Failure #2错误?
Hey there! Let's break down why you're hitting that stack corruption error and fix it right up. The issue boils down to two key mistakes in your code: unsafe input handling with scanf_s and misleading array initialization.
1. The Root Causes of the Stack Corruption
a. Unsafe scanf_s Call for the selection Array
You declared char selection[2];—this array can only hold 1 character plus the required null terminator (\0). But when you call:
scanf_s("%s", selection, strlen(selection));
strlen(selection)is undefined behavior here. The array isn't initialized, so its contents are random garbage from the stack. This means you're passing a random number as the buffer size toscanf_s.- If the user enters even a single character,
scanf_swill try to write that character plus a null terminator. If the random size value is larger than 2, you'll write beyond the array's bounds, corrupting the stack and triggering the Run-Time Check Failure #2.
b. Misleading seats Array Initialization
Your line int seats[11] = { 1 }; only initializes seats[0] to 1, and all other elements to 0. While this might work for your logic right now, it's unclear and could lead to bugs later. Since all seats start unoccupied, you should explicitly initialize every element to 0.
2. Step-by-Step Fixes
Fix the scanf_s Call for selection
Replace the unsafe scanf_s line with a version that uses the array's actual size, and clear leftover newline characters from the input buffer to avoid skipping future prompts:
// Clear leftover newline from the input buffer first while (getchar() != '\n'); printf("\nFirst Class is all booked\n\nDo you want to switch to Economy Class?\nEnter Y to confirm:"); // Limit input to 1 character and pass the array's actual size scanf_s("%1s", selection, (unsigned)_countof(selection));
Repeat this fix for the other scanf_s call in the economy class section.
Fix the seats Array Initialization
Change the initialization to explicitly set all elements to 0 (unoccupied):
int seats[11] = {0}; // All seats start as available
Bonus: Clean Up Integer Input Handling
When using scanf_s("%d", &input);, leftover newline characters can break subsequent %s or %c calls. Add a buffer clear right after this line:
scanf_s("%d", &input); // Clear any leftover newline to prevent input skipping while (getchar() != '\n');
3. Full Fixed Code
#include<stdio.h> #include<string.h> // Required for _countof macro int main(void) { // Declaring Variables int first = 1; int econ = 6; int input = 0; unsigned int counter = 0; // Initialize all seats to 0 (unoccupied state) int seats[11] = {0}; char selection[2]; printf("Welcome to our automated reservation system!\n"); // Loop until all 10 seats are booked while (counter < 10) { // Prompt user for cabin selection printf("Please type 1 for First Class.\nPlease type 2 for Economy Class:"); scanf_s("%d", &input); // Clear leftover newline from input buffer while (getchar() != '\n'); if (input == 1) { // Check for available first class seats if (!seats[first] && first <= 5) { printf("\nBoarding Pass:\nYour seat number is: %d in First Class\n\n", first); seats[first++] = 1; counter++; } // Offer economy if first class is full else if (first > 5 && econ <= 10) { printf("\nFirst Class is all booked\n\nDo you want to switch to Economy Class?\nEnter Y to confirm:"); scanf_s("%1s", selection, (unsigned)_countof(selection)); if (selection[0] == 'y' || selection[0] == 'Y') { printf("\nBoarding Pass:\nYour seat number is: %d in Economy Class\n\n", econ); seats[econ++] = 1; counter++; } else { printf("\nNext flight leaves in 3 hours.\n\n"); } } else { printf("\nNext flight leaves in 3 hours.\n\n"); } } // Handle economy class selection else if (input == 2) { // Check for available economy seats if (!seats[econ] && econ <= 10) { printf("\nBoarding Pass:\nYour seat number is: %d in Economy Class\n\n", econ); seats[econ++] = 1; counter++; } // Offer first class if economy is full else if (econ > 10 && first <= 5) { printf("\nEconomy Class is all booked\n\nDo you want to switch to First Class?\nEnter Y to confirm:"); scanf_s("%1s", selection, (unsigned)_countof(selection)); if (selection[0] == 'y' || selection[0] == 'Y') { printf("\nBoarding Pass:\nYour seat number is: %d in First Class\n\n", first); seats[first++] = 1; counter++; } else { printf("\nNext flight leaves in 3 hours.\n\n"); } } else { printf("\nNext flight leaves in 3 hours.\n\n"); } } else { printf("\nInvalid selection. Please try again.\n\n"); } } // Final message when all seats are booked printf("All seats for this flight are now booked\n\nPlease contact customer service for additional services.\nThank you for using our automated reservation system.\n"); return 0; }
Why This Works
- By using
_countof(selection)(which equals 2) inscanf_s, you guarantee you never write beyond the array's bounds, eliminating stack corruption. - Initializing
seatsto all 0s makes your code's intent clear and avoids unintended behavior from uninitialized memory. - Clearing the input buffer prevents leftover newline characters from causing odd behavior like skipping prompts.
内容的提问来源于stack exchange,提问作者Destiny

