István Csige
István Csige

Reputation: 79

Encountering undefined behavior on a function to add up numbers below 10

I am encountering UB in the terminal with my current code when the input contains comma, dot or non-only-numeric character. I am confused why that is happening.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

float tizAlatti(int inputCount);

int main(){
    int inputNumber;
    printf("Number of input elements: ");
    scanf("%d", &inputNumber);
    if(inputNumber % 1 != 0 && (isdigit(inputNumber) == 0)){
    printf("Error encountered.");
    exit(1);
    }
    printf("\n%.2f", tizAlatti(inputNumber));
}
float tizAlatti(int inputCount){
    float arr[inputCount], input = 0;
    printf("\n");
    for(int i = 0; i<inputCount; i++){
        printf("Element %d: ", i+1);
        scanf("%f", &arr[i]);
        if(arr[i] < 10){
            input+= arr[i];
        }
    }
    return input;
}

Here I got this output for "h" input. It's not its ASCII code value, which was a false assumption by me. "h" input

I also got this output for "5.6" input. "5.6" input

I worked out that the issue lays somewhere in the if() part in the main() function, as the tizAlatti function gets invoked in the main for an input, but I don't know what this problem exactly is. Any help is highly appreciated!

Upvotes: 1

Views: 49

Answers (1)

chux
chux

Reputation: 154602

I am encountering UB in the terminal with my current code when the input contains comma, dot or non-only-numeric character.

Neither scanf("%d", &inputNumber) nor scanf("%f", &arr[i]); ever read these characters*1, so they remain in stdin until something does read them. This also blocks following input.

As scanf("%d", &inputNumber) and scanf("%f", &arr[i]) then do not assign inputNumber or arr[i], that value is indeterminant leading to subsequent trouble.

Check the return value of scanf() and if not 1, exit or use other code to read/consume the non-numeric input and try again.

Even better, use fgets() to read a line of user input and stop using scanf() until you know why it is bad.


*1 '.' as a decimal point is read by scanf("%f", &arr[i]).

Upvotes: 1

Related Questions