Ad

C/C++ Run-Time Check Failure #2 - Stack Around The Variable 'gradeLetter' Was Corrupted. Visual Studio 2019. How To Solve This Problem?

- 1 answer

#include <stdio.h>
#pragma warning(disable:4996)

//Counting GPA
int main()
{
    float finalGrade, totalQualityPoints = 0, totalHours = 0;
    int hours, qualityPoints, subjectsCount, points = 0;
    char gradeLetter;

    printf("How many subjects do you have? ");
    scanf("%d", &subjectsCount);

    for (int i = 1; i <= subjectsCount; i++) {

        printf("\nEnter the number of hours for your %d subject: ", i);
        scanf("%d", &hours);
        printf("Enter the grade letter for your %d subject: ", i);
        scanf("%s", &gradeLetter);
        printf("\n");
        
        if (gradeLetter == 'A' || gradeLetter == 'a') {
            points = 4;
        } else if (gradeLetter == 'B' || gradeLetter == 'b') {
            points = 3;
        } else if (gradeLetter == 'C' || gradeLetter == 'c') {
            points = 2;
        } else if (gradeLetter == 'D' || gradeLetter == 'd') {
            points = 1;
        } else if (gradeLetter == 'F' || gradeLetter == 'f') {
            points = 0;
        }
        
        //At each iteration, this variable adds up the previous value for each subject
        qualityPoints = hours * points;
        totalHours += hours;
        totalQualityPoints += qualityPoints;

    }

    printf("\nTotal hours: %.2f Total QP: %.2f ",totalHours, totalQualityPoints);

    finalGrade = totalQualityPoints / totalHours;
    printf("\nYour GPA is: %.2f ", finalGrade);
}

Run-Time Check Failure #2 - Stack around the variable 'gradeLetter' was corrupted. Visual Studio 2019. How to solve this problem?

The output to the screen is carried out, the program actually reads and outputs gpa. But at the end the compiler outputs a warning

Ad

Answer

regarding:

scanf("%s", &gradeLetter);
  1. is expecting to read a single character, not a string
  2. needs to consume/discard any left over '\n' left in stdin

Suggest:

scanf(" %c", &gradeLetter);

Notice the use of the %c input format conversion specifier

Notice the space before the conversion specifier to consume any leading 'white space' like the left over '\n' in stdin

regarding the group of statements similar to:

if (gradeLetter == 'A' || gradeLetter == 'a') {

Suggest replacing that whole group with the single statement:

#include <ctype.h>
....
points = 5 - (tolower( gradeLetter ) - 'a' );
....
Ad
source: stackoverflow.com
Ad