0
votes

I was wondering if I can get some help on my program. As stated in the title, I'm getting an access violation in my program. I realize that it has something to do with dereferencing a garbage pointer, and I'm pretty sure I've narrowed down the line that its breaking on, I'm just not sure why it's actually breaking, and how to fix it. The code is as follows:

void determineInputType(char input[kMaxUserInput])
{
    char* flag = NULL;
    if (*(flag = strchr(input, '.')) != NULL)
    { 
        double grade = 0;
        if ((sscanf(input, "%lf", grade)) == 1)  // problem is on this line
        {
        //rest of the code continues here

How I'm getting the input is here:

void getUserInput(char* userInput)
{
    printf("Enter a student's grade: ");
    fgets(userInput, kMaxUserInput, stdin);
    clearCRLF(userInput);

}

and finally the main:

int main(void)
{
    char userInput[kMaxUserInput] = { 0 };
    getUserInput(userInput);
    determineInputType(userInput);

    return 0;
}

Any help on this would be greatly appreciated as it's been stumping me for a while. Thanks so much for your time, if there's anything else I need to post, let me know.

1
I also noticed another problem in this line: if (*(flag = strchr(input, '.')) != NULL) ... you are dereferencing the pointer flag while it may be NULL. You should change it into if ((flag = strchr(input, '.')) != NULL)tiguchi
Yeah that was me testing to see if that would fix the problem before, I should probably get rid of that.Hayden Taylor

1 Answers

3
votes

The scanf family requires you to supply a pointer to the value you want populated:

if ((sscanf(input, "%lf", &grade)) == 1)  // problem is no longer on this line

The way you have it, you set grade to zero then use that as the pointer.

The relevant part of the standard (C99 on which C++11 defers to) is 7.19.6.2 /12 (my bold):

a,e,f,g - Matches an optionally signed floating-point number, infinity, or NaN, whose format is the same as expected for the subject sequence of the strtod function. The corresponding argument shall be a pointer to floating.

l (ell) - Specifies that ... a following a, A, e, E, f, F, g, or G conversion specifier applies to an argument with type pointer to double; ...